Abh*_*jit 0 c++ file-io cygwin fstream
尝试使用fstream在C++中读取文件.但是is_open()函数总是返回0结果而readline()不会读取任何内容.请参阅下面的代码段.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
string line;
ifstream myfile("D:\xx\xx\xx\xx\testdata\task1.in.1");
if (myfile.is_open()) {
while (getline(myfile, line)) {
cout << line << '\n';
}
myfile.close();
}
else
cout << "Unable to open file";
return 0;
}
Run Code Online (Sandbox Code Playgroud)
你认为你正在开放 D:\<somepath>\testdata\task1.in.1
但实际上你正试图打开,D:\<somepath><tabulation char>estdata<tabulation char>ask1.in.1因为它\t被解释为制表.
(就像\n是换行符printf("hello world\n");)
(\x特别太BTW,这不是真正的道路或你会有另一个错误:error: \x used with no following hex digits可能会更好地与你交谈!)
你必须像这样逃避反斜杠:
D:\\xx\\xx\\xx\\xx\\testdata\\task1.in.1
Windows也接受这样的路径,更方便,除非你想用cd命令等生成需要反斜杠的批处理脚本(/在批处理命令中用作选项开关):
D:/xx/xx/xx/xx/testdata/task1.in.1
正如NathanOliver所述,如果您的编译器启用了C++ 11模式(或使用--std=c++11),则可以使用原始前缀
R"(D:\xx\xx\xx\xx\testdata\task1.in.1)"
最后一句话:肮脏的逃脱方式:
D:\Xx\Xx\Xx\Xx\Testdata\Task1.in.1
在这种情况下使用大写将起作用
但那只是运气.很多人没有意识到他们非常接近一个错误.顺便说一句,很多人都把windows路径大写(在这个网站上看得很多),因为他们注意到他们的路径在不知道原因的情况下不能用小写.