无法在C ++中读取.txt文件

时间:2018-08-21 06:28:01

标签: c++

我有一个.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也给我错误。

更改文件路径并将其流式传输到其他路径也会向我显示错误。

当我尝试从cmd读取文件时,将其CD到完整路径并输入文本文件名。我可以打开并正确阅读。因此,我觉得w.r.x是可以访问的,并且我对该文件拥有权限。

更新:

我知道了我的问题。谢谢大家的回答!

1 个答案:

答案 0 :(得分:1)

您需要双反斜杠或将文件路径声明为字符串文字。您可以这样做:

string myPath = L"C:\Users\(full path)\A3Data.txt";

作为字符串文字,或

string myPath = "C:\\Users\\(full path)\\A3Data.txt";

作为正确转义的文件路径

如果上述方法不起作用,并且您已确保拥有文件的正确路径,则可能没有文件的正确权限。您可以尝试以管理员身份运行命令行,然后从中执行代码,如果仍然失败,请告知我们。