在C++中打印从变量到文件的路径

Printing a path to a file from a variable in C++

本文关键字:文件 路径 变量 C++ 打印      更新时间:2023-10-16

假设我有这个函数:

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