Why do I have to use double backslashes for file-paths in code?

后端 未结 1 721
遥遥无期
遥遥无期 2020-12-16 21:25

In my program I\'m trying to open a file, for example C:\\unescaped\\backslashes.txt, but it fails to open! Why?

What is this?

This is a colle

相关标签:
1条回答
  • 2020-12-16 22:04

    This is the preliminary answer. It's community-wiki so feel free to improve it.

    Somewhere in your code you have a file-path that contains unescaped backslashes. For example:

    const char *fileName = "c:\unescaped\backslashes.txt";
    

    You need to change it into:

    const char *fileName = "c:\\unescaped\\backslashes.txt";
    

    Why?

    The compiler in C, C++, Java, Python and other languages treats the backslash as a special character, called the escape character.

    For example \n will be turned into a newline. So this code - printf("C:\new file.txt"); will print

    C:
    ew file.txt

    So if you have a file name that contains backslashes, what the program will receive will not be what you see in the source code. The backslash itself can be escaped with another backslash. So this code - printf("C:\\new file.txt"); will print this:

    C:\new file.txt
    0 讨论(0)
提交回复
热议问题