Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
566 views
in Technique[技术] by (71.8m points)

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

In my program I'm trying to open a file, for example C:unescapedackslashes.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:unescapedackslashes.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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:unescapedackslashes.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 will be turned into a newline. So this code - printf("C: ew 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:
ew file.txt

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...