Whenever I try to open a file with istream, it doesn't open (is_open() returns false). Is there a spec开发者_运维技巧ific 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();
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).
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");
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:
- Make sure
test.tx
t is in the same directory asa.out
- Check for
permissions
on test.txt andwhether it exists
.
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();
精彩评论