2

Lets say I have this function:

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();
}

I do not control the myPath argument. Right now it doesn't have \\ in the path name so the stream interprets them as escape sequence which is not what I want.

How can I use a std::wstring variable as a raw string?

If it was a string literal I could use R"C:\myPath\"but how do I achieve the same thing without a string literal?

A possible approach could be to loop through the path name and add an extra backslash where needed but surely c++ has something more robust and elegant..?

EDIT:

My problem was misdiagnosed. Turns out the backslashes don't cause any trouble what I had to add was:

#include <codecvt>
#include <locale>

const std::locale utf8_locale
        = std::locale(std::locale(), new std::codecvt_utf8<wchar_t>());
myFile.imbue(utf8_locale);

As explained here: Windows Unicode C++ Stream Output Failure

The file path now displays correctly, I thought using a wofstream took care of the locals for you so the non-ANSII characters would display correctly.

Community
  • 1
  • 1
Asics
  • 858
  • 1
  • 11
  • 20

2 Answers2

1

I would propose you simply replace \\ by /, they work the same (even better because they are valid on all platform):

void printPathToFile( std::wstring myPath )
{
    std::wstring mySafePath = myPath;
    std::replace( mySafePath.begin(), mySafePath.end(), '\\', '/');

    // then use mySafePath in the rest of the function....
}
jpo38
  • 20,821
  • 10
  • 70
  • 151
0

It does: boost filesystem. You use a path to pass, well, paths, around instead of strings. Here's the hello world for boost filesystem:

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 directory\n";

    else
      cout << p << "exists, but is neither a regular file nor a       directory\n";
  }
  else
    cout << p << "does not exist\n";

  return 0;
}

http://www.boost.org/doc/libs/1_58_0/libs/filesystem/doc/tutorial.html

Edit: note also that this library is being considered for addition to the standard, and can currently be used from the std::experimental namespace, depending on your compiler/standard library version: http://en.cppreference.com/w/cpp/header/experimental/filesystem

Nir Friedman
  • 17,108
  • 2
  • 44
  • 72