0

i fell on this singular issue: i have to write to a txt file on a path that is like "C:....\0-myfolder\subfolder\file.txt", where '0-myfolder' is the entire name of the folder

writing it as a normal path with double backslashes doesn't work because of the unwanted null character that gets read in the sequence. I tried to write to another folder in the same directory which name doesn't start with 0 and it works without problems, and unlickily i can't rename the folder for other reasons.

Is there a way to force c++ not to read a null character?

  • 3
    Did you try forward slash / ? `C:..../0-myfolder/subfolder/file.txt` – Tony Tannous Jun 25 '20 at 07:23
  • Just escape the \ character, replace all \ with \\ – Kaznov Jun 25 '20 at 07:31
  • If using double backslashes doesn't work, something else is wrong.Note that you need to escape *all* backslashes, not just the one before the `0`. – molbdnilo Jun 25 '20 at 07:57
  • Yep i used correctly the double backslashes instead of the single ones, as i said i also tried to read from another folder in the same directory of the 0-myfolder and it works.. even with forward slashes as suggested by @Tony it didn't work. I also made it write out the filename of the file i inserted and it is correct, i can just copy and paste it on the explorer and it opens the file. – Giovanni D.C. Jun 25 '20 at 09:10
  • Then there is something else that is wrong. Can you read it from within your program? Have you verified that you have write permissions to that file, and that it isn't opened elsewhere? Consider creating a [mcve]. – molbdnilo Jun 25 '20 at 12:47

1 Answers1

2

Using raw string literals may be a good solution:

#include <iostream>

int main(void)
{
   std::cout << R"(C:\0-myfolder\subfolder\file.txt)" << std::endl;
   return 0;
}

Handles escapes automatically producing the clean output C:\0-myfolder\subfolder\file.txt

see https://en.cppreference.com/w/cpp/language/string_literal

Åke
  • 36
  • 3
  • The string comes out correctly now thanks!! Anyway it doesn't find the file, still the string is correct.. i'm going to do some tests – Giovanni D.C. Jun 26 '20 at 08:16