ih8coding
ih8coding

Reputation: 27

Failed to read .txt file in C++

I have a .txt file and I tried using the absolute path "C:\Users\(full path)\A3Data" and static paths (shown in code):

#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;
}

Expected output: (contents in A3Data.txt)

Actual Output:

"A3Data.txt failed to open"

Double backslashing the absolute path e.g. C:\\Users\\(full path)\\A3Data.txt gives me the error too.

Changing the filepaths and ifstream-ing it to the different path also shows me the error.

When i tried to read my file from cmd, I cd'ed it to the full path and typed in the text file name. I could open & read it properly. Hence I feel that the w.r.x are accessible to me and I have rights to the file.

UPDATE:

I have figured out my issue. Thank you all for the answers!

Upvotes: 1

Views: 2458

Answers (1)

vividpk21
vividpk21

Reputation: 384

You need to double backslash or declare your file path as a string literal. You can do this like:

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

As a string literal, or

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

As a properly escaped file path

If the above does not work and you have guaranteed that you have the proper paths to the file then you may not have proper rights to the file. You could try running a command line as administrator and then executing your code from that, if that also fails let us know.

Upvotes: 1

Related Questions