C++ ifstream 不会打开文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14920106/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ifstream won't open file
提问by photon
I'm trying to open a file so I can read from it.
我正在尝试打开一个文件,以便我可以从中读取。
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
ifstream input_file("blah.txt", ios::in);
ofstream output_file("output.txt", ios::out);
Bank::Bank(void){
input_file.open("blah.txt");
if(!input_file){
cerr << "Error" << endl;
exit(1);
}
else{
cout << "good 2 go" << endl;
}
}
This is the code I have for reading the file named blah.txt and the output I'm getting at the terminal is the "Error". I am using Linux Mint 14 and gVim, so when I enter the :pwd command, I know I am in directory /mnt/share. Checking from the terminal, file blah.txt is in the same directory. The only thing I can think of is hidden file extensions. Why can't I open the file?
这是我用于读取名为 blah.txt 的文件的代码,我在终端得到的输出是“错误”。我使用的是 Linux Mint 14 和 gVim,所以当我输入 :pwd 命令时,我知道我在目录 /mnt/share 中。从终端检查,文件 blah.txt 位于同一目录中。我唯一能想到的是隐藏文件扩展名。为什么我打不开文件?
回答by Hui Zheng
That's because you open "blah.txt" twice.
那是因为你打开了“blah.txt”两次。
First time:
第一次:
ifstream input_file("blah.txt", ios::in)
ifstream input_file("blah.txt", ios::in)
Second time:
第二次:
input_file.open("blah.txt")
input_file.open("blah.txt")
Removing the second one should fix your problem.
删除第二个应该可以解决您的问题。
回答by Alexey Frunze
This
这个
ifstream input_file("blah.txt", ios::in);
Additionally, when the second constructor version is used, the stream is associated with a physical file as if a call to the member function open with the same parameters was made.
此外,当使用第二个构造函数版本时,流与物理文件相关联,就像调用了具有相同参数的成员函数 open 一样。
This
这个
input_file.open("blah.txt");
应该失败:
If the object already has a file associated (open), the function fails.
如果对象已经关联了(打开)文件,则该函数失败。
Please read the documentation.
请阅读文档。