我有一个 .txt 文件,我尝试使用绝对路径“C:\Users\(完整路径)\A3Data”和静态路径(如代码所示):
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
string line;
ifstream MyReadFile("A3Data.txt");
if(MyReadFile.is_open()) //checks whether file is being opened
{
while (getline(MyReadFile, line)) //uses getline to get the string values from the .txt file to read line by line
{
cout << line << '\n';
}
MyReadFile.close();
}
else if (MyReadFile.fail())
{
cout << "A3Data.txt failed to open" << endl;
}
return 0;
}
预期输出:
(A3Data.txt
中的内容)
实际输出:
"A3Data.txt failed to open"
双反斜杠绝对路径,例如C:\\Users\\(full path)\\A3Data.txt
也给我错误。
更改文件路径并将其 ifstream-ing 到不同的路径也会显示错误。
当我尝试从 cmd 读取我的文件时,我将其 cd 到完整路径并输入文本文件名。我可以打开并正确阅读它。因此,我觉得我可以访问 w.r.x,并且我有权访问该文件。
更新:
我已经解决了我的问题。谢谢大家的回答!
最佳答案
您需要双反斜杠或将您的文件路径声明为字符串文字。你可以这样做:
string myPath = L"C:\Users\(full path)\A3Data.txt";
作为字符串文字,或者
string myPath = "C:\\Users\\(full path)\\A3Data.txt";
作为正确转义的文件路径
如果上述方法不起作用,并且您已保证您拥有正确的文件路径,那么您可能没有该文件的正确权限。您可以尝试以管理员身份运行命令行,然后从中执行您的代码,如果仍然失败,请告诉我们。
关于c++ - 无法在 C++ 中读取 .txt 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51942795/