跳至主要內容

24.C++文件和流

约 210 字小于 1 分钟

文件操作

C++ 提供了 <fstream> 头文件来支持文件操作,主要包含以下三个类:

ofstream(输出文件流,写入文件)
ifstream(输入文件流,读取文件)
fstream(文件流,同时支持读写)

文件写入

#include <fstream>
#include <iostream>

int main() {
    std::ofstream outFile("example.txt"); // 创建文件并打开
    if (!outFile) {
        std::cerr << "文件打开失败!" << std::endl;
        return 1;
    }

    outFile << "Hello, C++ 文件操作!" << std::endl;
    outFile << "写入第二行文本。" << std::endl;

    outFile.close(); // 关闭文件
    std::cout << "文件写入完成。" << std::endl;
    return 0;
}

文件读取

#include <fstream>
#include <iostream>
#include <string>

int main() {
    std::ifstream inFile("example.txt"); // 以读取模式打开文件
    if (!inFile) {
        std::cerr << "文件打开失败!" << std::endl;
        return 1;
    }

    std::string line;
    while (std::getline(inFile, line)) { // 逐行读取文件
        std::cout << line << std::endl;
    }

    inFile.close(); // 关闭文件
    return 0;
}