为什么我必须在代码中使用双反斜杠作为文件路径? [英] Why do I have to use double backslashes for file-paths in code?

查看:223
本文介绍了为什么我必须在代码中使用双反斜杠作为文件路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的程序中,我试图打开一个文件,例如 C:\unescaped\backsl.txt ,但是无法打开!为什么?



这是什么?



这是常见问答的集合。这也是一个社区维基,所以每个人都被邀请参加维护。



为什么是这样?



网站中有很多问题归结为OP,不知道他/她需要在源代码中的文件路径中转义反斜杠。问题通常是为什么我的程序不工作?或者为什么找不到文件?,源代码中的某个地方将会有:

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



范围如何?



适用于C,C ++,Java,Python和其他编译器将反斜杠视为转义字符的语言。



元标题为参考 - 关于所有精确重复的提案;文件名中的双反斜杠问题

解决方案

这是初步的答案。它是社区维基,所以随意改进它。



你的代码中有一个文件路径包含未转义的反斜杠。例如:

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

您需要将其更改为:

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



为什么?



C中的编译器,C ++,Java,Python和其他语言将反斜杠视为特殊字符,称为转义字符



例如 \\\
将变成换行符。所以这个代码 - printf(C:\\\
ew file.txt);
将打印

 C:
ew file.txt

所以如果你有一个包含反斜杠的文件名,程序将收到什么不会是你看源码。反斜杠本身可以用另一个反斜杠进行转义。所以这个代码 - printf(C:\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ pre> C:\\\
ew file.txt


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

解决方案

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

这篇关于为什么我必须在代码中使用双反斜杠作为文件路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆