我想打开一个文件并从中读取一行。文件中只有一行,所以我真的不需要担心循环,尽管为了将来的引用,知道如何读取多行会很好。
int main(int argc, const char* argv[]) {
// argv[1] holds the file name from the command prompt
int number = 0; // number must be positive!
// create input file stream and open file
ifstream ifs;
ifs.open(argv[1]);
if (ifs == NULL) {
// Unable to open file
exit(1);
} else {
// file opened
// read file and get number
...?
// done using file, close it
ifs.close();
}
}
我该怎么做?另外,就成功打开而言,我是否正确处理打开的文件?
谢谢。
最佳答案
有几件事:
您可以使用
>>
流提取运算符读取数字:ifs >> number
。标准库函数getline如果您想要整行文本,将从文件中读取一行。
要检查文件是否打开,只需编写
if (ifs)
或if (!ifs)
。省略== NULL
。您不需要在最后显式关闭文件。当
ifs
变量超出范围时,这会自动发生。
修改后的代码:
if (!ifs) {
// Unable to open file.
} else if (ifs >> number) {
// Read the number.
} else {
// Failed to read number.
}
关于c++ - 如何在 C++ 中使用 ifstream 打开和读取文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3327709/