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

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

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

谢谢。

最佳答案

有几件事:

  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.
}

关于c++ - 如何在 C++ 中使用 ifstream 打开和读取文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3327709/

相关文章:

c++ - Windows std::ifstream::open() 问题

c++ - 如何在读取文件时打印数组

C++容器/迭代器依赖问题

java - .exists() 方法总是返回 false

c++ - 从文件中读取数据时检查一行是否完成

file-io - 将 clojure 映射/数组写入文件并读取它们

c++ - pthread_create 模板函数——静态转换模板类

c++ - Sfml 碰撞 : when the player hits a square, 他只是停止移动

C++ 新的内存分配碎片

c++ - 如何在包含的 C++ 源代码中写入外部文件的路径