0

In the following program, it writes data successfully to student.txt file, but when I open it and print line by line of the file, it always shows file not found.

Could anyone help me with that?

    ifstream Myfile;


    Myfile.open("student.txt");


      if(!Myfile){
        cout<<"Sorry file can't be opened" <<endl;

        exit(1);
    }


        else
        { 

            // Use loop and read the names and ids from the file and display them 
        string line;
        while (getline(Myfile, line)){

        cout<<line<<endl;
    }

            // Close the file 
      Myfile.close();    
Alex Kulinkovich
  • 4,408
  • 15
  • 46
  • 50
Goola
  • 27
  • 3

2 Answers2

3

Check where your file is placed. Depending on IDE program can look for file in the root folder of the project or in the folder where compiled binaries are situated.

or

Simply specify the full path to the file.

Tigerjz32
  • 4,324
  • 4
  • 26
  • 34
0

Your application has a "Working Directory". This is the directory in which it tries to open files.

In your case the file is probably not in the "Working Directory" of the running application. So the solution is:

  • Put the file in the "Working Directory" of the application
  • Change the application "Working Directory".
  • Use an Absolute Path for the file name.

Also see: How do I get the directory that a program is running from?

Martin York
  • 257,169
  • 86
  • 333
  • 562