C++ 文件 I/O

概述

C++ 通过 fstream 库提供全面的文件 I/O 功能,支持文本和二进制文件操作。

文本文件操作

写入文本文件

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

int main() {
    // 写入文本文件
    std::ofstream outFile("example.txt");

    if (!outFile) {
        std::cout << "Error opening file for writing!" << std::endl;
        return 1;
    }

    outFile << "Hello, World!" << std::endl;
    outFile << "This is a C++ file I/O example." << std::endl;
    outFile << "Number: " << 42 << std::endl;
    outFile << "Pi: " << 3.14159 << std::endl;

    outFile.close();
    std::cout << "Data written to file successfully." << std::endl;

    return 0;
}

从文本文件读取

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

int main() {
    // 从文本文件读取
    std::ifstream inFile("example.txt");

    if (!inFile) {
        std::cout << "Error opening file for reading!" << std::endl;
        return 1;
    }

    std::string line;
    std::cout << "File contents:" << std::endl;

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

    inFile.close();

    return 0;
}

读取格式化数据

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

int main() {
    std::ifstream inFile("data.txt");

    if (!inFile) {
        std::cout << "Error opening file!" << std::endl;
        return 1;
    }

    std::string name;
    int age;
    double salary;

    // 读取格式化数据
    inFile >> name >> age >> salary;

    std::cout << "Name: " << name << std::endl;
    std::cout << "Age: " << age << std::endl;
    std::cout << "Salary: " << salary << std::endl;

    inFile.close();

    return 0;
}

二进制文件操作

写入二进制文件

#include <iostream>
#include <fstream>
#include <vector>

struct Person {
    char name[50];
    int age;
    double salary;
};

int main() {
    Person person = {"John Doe", 30, 50000.0};

    // 写入二进制数据
    std::ofstream outFile("person.dat", std::ios::binary);

    if (!outFile) {
        std::cout << "Error opening binary file for writing!" << std::endl;
        return 1;
    }

    outFile.write(reinterpret_cast<char*>(&person), sizeof(Person));
    outFile.close();

    std::cout << "Binary data written successfully." << std::endl;

    return 0;
}

读取二进制文件

#include <iostream>
#include <fstream>

struct Person {
    char name[50];
    int age;
    double salary;
};

int main() {
    Person person;

    // 读取二进制数据
    std::ifstream inFile("person.dat", std::ios::binary);

    if (!inFile) {
        std::cout << "Error opening binary file for reading!" << std::endl;
        return 1;
    }

    inFile.read(reinterpret_cast<char*>(&person), sizeof(Person));
    inFile.close();

    std::cout << "Name: " << person.name << std::endl;
    std::cout << "Age: " << person.age << std::endl;
    std::cout << "Salary: " << person.salary << std::endl;

    return 0;
}

文件定位

随机访问

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

int main() {
    std::fstream file("random.txt", std::ios::in | std::ios::out | std::ios::binary);

    if (!file) {
        std::cout << "Error opening file!" << std::endl;
        return 1;
    }

    // 写入一些数据
    file << "Hello, C++ File I/O!";

    // 获取当前位置
    std::streampos pos = file.tellp();
    std::cout << "Current position: " << pos << std::endl;

    // 移动到开始位置
    file.seekp(0, std::ios::beg);

    // 覆盖前 5 个字符
    file.write("Hi!!!", 5);

    // 移动到特定位置
    file.seekp(7, std::ios::beg);
    file.write("World", 5);

    file.close();

    // 读取修改后的文件
    std::ifstream inFile("random.txt");
    std::string content;
    std::getline(inFile, content);
    std::cout << "Modified content: " << content << std::endl;

    return 0;
}

文件流状态

检查文件状态

#include <iostream>
#include <fstream>

int main() {
    std::ifstream inFile("nonexistent.txt");

    // 检查文件状态
    if (!inFile) {
        std::cout << "File could not be opened!" << std::endl;

        if (inFile.fail()) {
            std::cout << "Fail bit set" << std::endl;
        }

        if (inFile.bad()) {
            std::cout << "Bad bit set" << std::endl;
        }
    }

    // 清除错误状态
    inFile.clear();

    return 0;
}

高级文件操作

处理大文件

#include <iostream>
#include <fstream>
#include <vector>

int main() {
    std::ifstream inFile("large_file.txt");

    if (!inFile) {
        std::cout << "Error opening file!" << std::endl;
        return 1;
    }

    // 获取文件大小
    inFile.seekg(0, std::ios::end);
    std::streamsize fileSize = inFile.tellg();
    inFile.seekg(0, std::ios::beg);

    std::cout << "File size: " << fileSize << " bytes" << std::endl;

    // 将整个文件读入缓冲区
    std::vector<char> buffer(fileSize);
    inFile.read(buffer.data(), fileSize);

    // 处理数据
    std::string content(buffer.begin(), buffer.end());
    std::cout << "First 100 characters: " << content.substr(0, 100) << std::endl;

    inFile.close();

    return 0;
}

文件复制操作

#include <iostream>
#include <fstream>

int main() {
    std::ifstream src("source.txt", std::ios::binary);
    std::ofstream dest("destination.txt", std::ios::binary);

    if (!src || !dest) {
        std::cout << "Error opening files!" << std::endl;
        return 1;
    }

    // 复制文件内容
    dest << src.rdbuf();

    src.close();
    dest.close();

    std::cout << "File copied successfully!" << std::endl;

    return 0;
}