pighead10
pighead10

Reputation: 4305

Very basic file i/o

Whenever I try to open a file with istream, it doesn't open (is_open() returns false). Is there a specific directory a file needs to be put for it to be accessed (it's in the project's output directory)?

ifstream ifile;
ifile.open("test.txt");
if(!ifile.is_open()){
    cout << "The file could not be opened." << endl;
}
cin.get();

Upvotes: 1

Views: 163

Answers (4)

Sriram
Sriram

Reputation: 10578

I work on a Linux machine, and having the file test.txt in the same directory as the binary always works. So, if the executable for your project is named a.out, then the following two steps should make it work:

  1. Make sure test.txt is in the same directory as a.out
  2. Check for permissions on test.txt and whether it exists.

Upvotes: 2

Viktor Apoyan
Viktor Apoyan

Reputation: 10755

Try change this line ifile.open("test.txt"); -> ifile.open("/test.txt");

ifstream ifile;
ifile.open("/test.txt");
if(!ifile.is_open()){
    cout << "The file could not be opened." << endl;
}
cin.get();

Upvotes: 1

John Zwinck
John Zwinck

Reputation: 249642

It needs to be in the program's "working directory." This is either the directory where you are when you run the program, or if you're using an IDE like Visual Studio, the project's directory (the directory which also contains the Release and/or Debug build folders).

Upvotes: 4

user2100815
user2100815

Reputation:

You need to supply the correct path to the file. I don't know what your project's structure is, but something like:

ifile.open("output/test.txt");

Upvotes: 2

Related Questions