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

谁说胖子不能爱 提交于 2019-11-27 18:25:52

问题


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 collection of common Q&A. This is also a Community Wiki, so everyone is invited to participate in maintaining it.

Why is this?

There are a lot of questions in the site which boil down to OP not knowing he/she needs to escape backslashes in file paths in the source code. The questions are usually "Why is my program not working?" or "Why is the file not found?", and somewhere in the source code there will be:

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

What's the scope?

This question is applicable for C, C++, Java, Python, and others languages where the compiler treats backslash as the escape character.

Meta post for reference - Proposal for exact-duplicate sink for all the "double-backslashes in filename" questions


回答1:


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


来源:https://stackoverflow.com/questions/28328052/why-do-i-have-to-use-double-backslashes-for-file-paths-in-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!