简体   繁体   English

如何使用 visual studio c++ 打开特定文件夹中的文件 txt?

[英]How do I open a file txt in a specific folder using visual studio c++?

This is the part of code where I try to open the file f1.txt, it is complete path is C:\Users\Hp\Desktop\NSGA2-CDS\DataSet\f1.txt这是我尝试打开文件 f1.txt 的代码部分,它的完整路径是 C:\Users\Hp\Desktop\NSGA2-CDS\DataSet\f1.txt

ifstream fichier("C:\Users\Hp\Desktop\NSGA2-CDS\DataSet\f1.txt", ios::in);

The file cannot be opened and I don't know why?!文件无法打开,我不知道为什么?!

NSGA2-CDS is the folder that contain the visual studio solution NSGA2-CDS 是包含 visual studio 解决方案的文件夹

You have to escape backslashes in the path string:您必须转义路径字符串中的反斜杠:

ifstream fichier("C:\\Users\\Hp\\Desktop\\NSGA2-CDS\\DataSet\\f1.txt", ios::in);

This has nothing to do with file I/O as such;这与文件 I/O 本身无关; it's a feature of string literals: \ is used to escape special characters (such as \n , \t ), so when it appears in a string, it needs to be escaped as well.这是字符串文字的一个特性: \用于转义特殊字符(例如\n\t ),因此当它出现在字符串中时,也需要对其进行转义。

you can also use raw string literal so you don't need to escape individual char.您还可以使用原始字符串文字,这样您就不需要转义单个字符。

ifstream fichier(R"(C:\Users\Hp\Desktop\NSGA2-CDS\DataSet\f1.txt)", ios::in);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM