开发者

Very basic file i/o

开发者 https://www.devze.com 2023-02-28 07:58 出处:网络
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\

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:

  1. Make sure test.txt is in the same directory as a.out
  2. Check for permissions on test.txt and whether 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();
0

精彩评论

暂无评论...
验证码 换一张
取 消