Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading File in C++

Tags:

c++

I am unable to figure out why my code is not able to open and read a file. What am i missing?

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main (int argc, char * const argv[]) 
{
    string line;
    ifstream myfile ("input_file_1.txt");
    if (myfile.is_open())
    {
        while (!myfile.eof())
        {
            getline (myfile,line);
            cout << line << endl;
        }
    }
    else
    {
        cout << "Was unable to open the file" << endl;
    }

    return 0;
}

The file "input_file_1.txt" is int he same directory as my .cpp file and it has read permissions. I even gave gave it 777 permissions and i was unable to read it.

Can anyone tell me what i am doing wrong? I really cannot figure it out....

like image 378
gprime Avatar asked Dec 09 '22 14:12

gprime


2 Answers

  • Try to use full path for the file
  • The default location to look for the file is where the executable is , not where the source is.
like image 159
Lior Kogan Avatar answered Dec 12 '22 04:12

Lior Kogan


How and where do you execute your program? From a IDE? Can you run the program from the same directory where you have your text file. Another possibility is to use an absolute path to the file.

like image 35
David Feurle Avatar answered Dec 12 '22 04:12

David Feurle