在C++中打印从变量到文件的路径
Printing a path to a file from a variable in C++
假设我有这个函数:
void printPathToFile( std::wstring myPath ){
std::wstringstream ss;
ss << myPath;
//When printing myPath as soon as there is a it stops so this information is lost.
ss << getOtherReleventLogingInformation();
std::wofstream myfile;
myfile.open ("C:\log.txt", std::wofstream::app|std::wofstream::out);
myfile << ss.str();
myfile.close();
}
我不控制myPath
参数。现在它的路径名中没有\
,所以流将它们解释为转义序列,这不是我想要的。
如何使用std::wstring变量作为原始字符串?
如果是字符串文字,我可以使用R"C:myPath"
,但如果没有字符串文字,如何实现同样的效果?
一种可能的方法是循环遍历路径名,并在需要的地方添加一个额外的反斜杠,但c++肯定有更健壮、更优雅的东西。。?
编辑:
我的问题被误诊了。事实证明反斜杠不会造成任何麻烦,我必须添加的是:
#include <codecvt>
#include <locale>
const std::locale utf8_locale
= std::locale(std::locale(), new std::codecvt_utf8<wchar_t>());
myFile.imbue(utf8_locale);
如这里所解释的:Windows Unicode C++流输出失败
文件路径现在可以正确显示了,我认为使用wofstream
可以为您处理本地文件,这样非ANSII字符就可以正确显示。
我建议您简单地用/
替换\
,它们的工作原理相同(甚至更好,因为它们在所有平台上都有效(:
void printPathToFile( std::wstring myPath )
{
std::wstring mySafePath = myPath;
std::replace( mySafePath.begin(), mySafePath.end(), '', '/');
// then use mySafePath in the rest of the function....
}
它确实:提升文件系统。使用path
传递路径,而不是字符串。以下是boost文件系统的你好世界:
int main(int argc, char* argv[])
{
path p (argv[1]); // p reads clearer than argv[1] in the following code
if (exists(p)) // does p actually exist?
{
if (is_regular_file(p)) // is p a regular file?
cout << p << " size is " << file_size(p) << 'n';
else if (is_directory(p)) // is p a directory?
cout << p << "is a directoryn";
else
cout << p << "exists, but is neither a regular file nor a directoryn";
}
else
cout << p << "does not existn";
return 0;
}
http://www.boost.org/doc/libs/1_58_0/libs/filesystem/doc/tutorial.html
编辑:还要注意,这个库正在考虑添加到标准中,目前可以从std::实验命名空间中使用,具体取决于编译器/标准库的版本:http://en.cppreference.com/w/cpp/header/experimental/filesystem
相关文章:
- 从函数角度看ID到文件路径的内部与外部映射
- 在C++中设置基于操作系统的文件路径
- Windows 非 ASCII 文件路径
- 非 ASCII 文件路径窗口
- C++和带有国家符号的文件路径(也许用 UTF8 编码)
- 如何为文件路径使用变量?
- 包括 VS Code 上的完整文件路径
- 如何使用提升获取当前文件路径?
- 如何在 c++ 中获取当前文件路径?
- 保存json文件后如何返回文件路径
- 从 C++ 中的文件路径中提取文件名
- 是否可以将文件路径传递给Qt中的setStyleSheet()
- 无法转换 .CATPart 文件.错误:输入文件路径似乎包含不支持的字符
- 在结构函数之间传递文件路径 C++ 编辑:修复LNK2019错误
- 提供依赖于输入的程序的文件路径
- 从 QFileSystemModel 中的文件路径和文件名获取 QModelIndex
- 如何更改变量文件名的文件路径?
- cmake:包括vs vs add_subDirectory:相对标头文件路径
- 在OSX中使用CGDisplayStream存储屏幕记录的特定文件路径
- 如何在另一个系统上启用文件路径