如何在C++中使用ifstream打开和读取文件?

Hri*_*sto 2 c++ file-io ifstream

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

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

我该怎么做?另外,我是否在成功打开时正确处理文件?

谢谢.

Joh*_*ica 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.
}
Run Code Online (Sandbox Code Playgroud)