Realto Realto - 17 days ago 9
C++ Question

Problems with reading a .txt file

I am looking for an answer to my question, but i didn't find it in any other place.

I'm trying to read from a .txt file, that is located in the same directory as my project files.

I wrote this simple code:

ifstream file("file.txt");
std::string line;
std::getline(file, line);
cout << line;


...but unfortunately, nothing happened, not even an error or crashing.

Upon exploring a little further... even if I change the name of the txt("file") file, to the name of a file that doesn't exist, nothing happens.

What am I missing?

Answer

if your error is due to opening file then provide full path to the file and check.

in your code you are reading the first line so if it is a white space then you can see nothing as output.

you must to iterate over each line until the last line (reaching the end of file EOF).

// let's say your file is "test.txt" which is located in D\\MyDB
// ifstream file("file.txt");

ifstream file("D:\\MyDB\\test.txt"); // use full path instead and check manully whether the file is there or not
std::string line;

if(file.fail())
    cout << "Opening file failed!" << endl;
else  
    while(std::getline(file, line))
    {
        cout << line;
    }

if it works when providing the full path then your current path is not the same as your project.

you can change the current directory using some API so if you are on windows then use: SetCurrentDirectory(path); and on linux use: chdir(sDirectory.c_str());

** I mean compilers not OS