c++filepathnull-character

C++ Writing to file with an unwanted null character inside the pathname


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?


Solution

  • 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