2

我想打开一个文件并从中读取一行。文件中只有一行,所以我真的不需要担心循环,尽管为了将来参考,知道如何读取多行会很好。

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();
    }
}

我该怎么做?另外,就成功打开而言,我是否正确处理了文件打开?

谢谢。

4

2 回答 2

5

有几件事:

  1. 您可以使用>>流提取运算符读取数字:ifs >> number

  2. 如果您想要一整行文本,标准库函数getline将从文件中读取一行。

  3. 要检查文件是否打开,只需写入if (ifs)if (!ifs). 省略== NULL.

  4. 您不需要在最后显式关闭文件。ifs当变量超出范围时,这将自动发生。

修改后的代码:

if (!ifs) {
    // Unable to open file.
} else if (ifs >> number) {
    // Read the number.
} else {
    // Failed to read number.
}
于 2010-07-25T02:05:18.147 回答
1

对于您在这里所做的事情,只需:

ifs >> number;

将从流中提取一个数字并将其存储在“数字”中。

循环播放,取决于内容。如果都是数字,例如:

int x = 0;
while (ifs >> numbers[x] && x < MAX_NUMBERS)
{
 ifs >> number[x];
 x++;
}

可以将一系列数字存储在数组中。这是有效的,因为如果提取成功,提取操作符的副作用为真,如果提取失败,则为假(由于文件结尾或磁盘错误等)

于 2010-07-25T02:09:05.907 回答