用C++实现文件读写操作

        文件读写操作是C++编程中非常常见的操作之一。下面是一个简单的示例,演示如何使用C++读取和写入文件。

读取文件:

#include <iostream>
#include <fstream>

int main() {
    std::ifstream inputFile("input.txt");

    if (!inputFile) {
        std::cerr << "Cannot open the input file." << std::endl;
        return 1;
    }

    std::string line;

    while (std::getline(inputFile, line)) {
        std::cout << line << std::endl;
    }

    inputFile.close();

    return 0;
}

        上述示例代码中,我们使用了std::ifstream类来打开输入文件,如果打开失败,程序将终止并输出错误信息。然后,我们使用std::getline函数从文件中读取每一行并输出到标准输出流。

写入文件:

#include <iostream>
#include <fstream>

int main() {
    std::ofstream outputFile("output.txt");

    if (!outputFile) {
        std::cerr << "Cannot create the output file." << std::endl;
        return 1;
    }

    outputFile << "Hello, World!" << std::endl;

    outputFile.close();

    return 0;
}

        上述示例代码中,我们使用了std::ofstream类来创建输出文件,如果创建失败,程序将终止并输出错误信息。然后,我们使用&lt;&lt;运算符向文件中写入字符串"Hello, World!"并在最后添加一个换行符。最后,我们关闭文件。

        注意:在使用文件读写操作进行文件处理时,应该使用完毕后及时关闭文件。操作完毕后,我们应该始终调用close函数关闭文件。

猜你喜欢

转载自blog.csdn.net/SYC20110120/article/details/133424943