[英]how do I open and read a file using ifstream in C++?
我想打开一个文件并从中读取一行。 该文件中只有一行,因此我真的不需要担心循环,尽管为将来参考,最好知道如何读取多行。
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.
}
对于您在这里所做的事情,只需:
ifs >> number;
将从流中提取一个数字并将其存储在“数字”中。
循环播放,取决于内容。 如果是所有数字,则类似:
int x = 0;
while (ifs >> numbers[x] && x < MAX_NUMBERS)
{
ifs >> number[x];
x++;
}
可以将一系列数字存储在数组中。 之所以起作用,是因为如果提取成功,则提取操作符的副作用为true,否则为false(由于文件或磁盘错误结束等)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.