A problem with reading from a file in c++



"data.txt"
1
2
This is a line.
This is another line.  


"main.cpp"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () {
  string line;
  ifstream myfile ("data.txt");
  if (myfile.is_open())
  {
    while ( myfile.good() )
    {
      getline (myfile,line);
      cout << line << endl;
    }
    myfile.close();
  }

  else cout << "Unable to open file"; 

  return 0;
}



Hello,

I've been facing a weird problem. When I run my code it just goes to the else statement that says "Unable to open file" but when I start debugging I realized that it actually reads just fine! Does anyone know how to fix this problem?
In VC2010 for me, the debugging directory is not the same as my build directory. So when I hit CTRL+F5 it would run from a different spot. My guess is that the data.txt is in the wrong folder.
where should the data.txt file be? shouldn't be in the folder where main.cpp is?
OK so now I created a new code which actually opens the file successfully. When I run the code w/o debugging it doesn't go the "while"loop. But when I debug it, it just works fine!!!!!!! OHHHH that's weird!!!!!!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
int main () {
  int i;
   char *inname = "data.txt";
    ifstream infile(inname);

    if (!infile) {
        cout << "There was a problem opening file "
             << inname
             << " for reading."
             << endl;
        return 0;
    }
    cout << "Opened " << inname << " for reading." << endl;
    while (infile >> i) {
        cout << "Value from file is " << i << endl;
    }
    return 0;
}


1
2
3
3
4
5


CAN ANYONE TRY TO RUN THE SAME CODE IN THEIR COMPUTER and SEE IF IT WORKS OR NOT? PLEASE!!!
Last edited on
did anyone try it yet? I'm still waiting for responses! it's due tomorrow morning and I'll stay awake until it gets solved
It's most likely that the executable program is in a different folder (directory) than the data file.

The release and debug versions will create a separate program, each in its own folder.

One simple fix is the copy the data file into the relevant folder. Another is to specify the full path (not relative path) when opening the file.
If you're using visual studio, the debugging will run from the same directory as the source (.cpp) files by default. If you actually run the excecutable, the file needs to be in the same directory as your .exe.
Topic archived. No new replies allowed.