非常基本的文件 I/O
每当我尝试使用 istream 打开文件时,它都不会打开(is_open() 返回 false)。是否需要将文件放置在特定目录中才能访问该文件(位于项目的输出目录中)?
ifstream ifile;
ifile.open("test.txt");
if(!ifile.is_open()){
cout << "The file could not be opened." << endl;
}
cin.get();
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();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
它需要位于程序的“工作目录”中。这是运行程序时所在的目录,或者如果您使用的是 Visual Studio 之类的 IDE,则为项目的目录(该目录还包含“发布”和/或“调试”构建文件夹)。
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:
我在 Linux 机器上工作,并且将文件
test.txt
放在与二进制文件相同的目录中总是有效的。因此,如果您的项目的可执行文件名为a.out
,那么以下两个步骤应使其正常工作:test.tx
t 与a.out
权限
以及是否存在
。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 nameda.out
, then the following two steps should make it work:test.tx
t is in the same directory asa.out
permissions
on test.txt andwhether it exists
.尝试更改此行 ifile.open("test.txt"); -> ifile.open("/test.txt");
Try change this line ifile.open("test.txt"); -> ifile.open("/test.txt");