c++怎么读取文件里的内容和往文件里写入数据

在 C++ 中,读取和写入文件主要通过 <fstream> 头文件提供的类来实现。以下是详细的方法和示例:

1. 包含必要的头文件

cpp 复制代码
#include <fstream>  // 文件流操作
#include <string>   // 使用字符串
#include <iostream> // 输入输出

2. 写入文件

使用 ofstream (输出文件流)

cpp 复制代码
#include <fstream>
#include <iostream>

int main() {
    // 创建输出文件流对象
    std::ofstream outFile;
    
    // 打开文件(如果文件不存在会自动创建)
    outFile.open("example.txt");
    
    // 检查文件是否成功打开
    if (!outFile.is_open()) {
        std::cout << "无法打开文件!" << std::endl;
        return 1;
    }
    
    // 写入数据
    outFile << "Hello, World!" << std::endl;
    outFile << "这是第二行" << std::endl;
    outFile << 123 << " " << 45.67 << std::endl;
    
    // 关闭文件
    outFile.close();
    
    std::cout << "数据写入成功!" << std::endl;
    return 0;
}

简化的写入方式

cpp 复制代码
#include <fstream>

int main() {
    // 使用构造函数直接打开文件
    std::ofstream outFile("example.txt");
    
    if (outFile) {  // 检查文件是否成功打开
        outFile << "简化方式写入数据" << std::endl;
        outFile << "自动会在析构时关闭文件" << std::endl;
    }
    
    return 0;
}

3. 读取文件

使用 ifstream (输入文件流)

cpp 复制代码
#include <fstream>
#include <iostream>
#include <string>

int main() {
    // 创建输入文件流对象
    std::ifstream inFile;
    inFile.open("example.txt");
    
    if (!inFile.is_open()) {
        std::cout << "无法打开文件!" << std::endl;
        return 1;
    }
    
    std::string line;
    
    // 逐行读取文件内容
    while (std::getline(inFile, line)) {
        std::cout << line << std::endl;
    }
    
    inFile.close();
    return 0;
}

其他读取方式

cpp 复制代码
#include <fstream>
#include <iostream>
#include <string>

int main() {
    std::ifstream inFile("example.txt");
    
    if (inFile) {
        // 方式1:逐词读取
        std::string word;
        while (inFile >> word) {
            std::cout << "单词: " << word << std::endl;
        }
        
        // 清空文件状态并重新定位到开头
        inFile.clear();
        inFile.seekg(0);
        
        // 方式2:读取单个字符
        char ch;
        while (inFile.get(ch)) {
            std::cout << ch;
        }
    }
    
    return 0;
}

4. 同时读写文件

使用 fstream

cpp 复制代码
#include <fstream>
#include <iostream>

int main() {
    // 打开文件用于读写
    std::fstream file("data.txt", std::ios::in | std::ios::out | std::ios::app);
    
    if (file.is_open()) {
        // 写入数据
        file << "新数据" << std::endl;
        
        // 移动到文件开头
        file.seekg(0);
        
        // 读取数据
        std::string content;
        while (std::getline(file, content)) {
            std::cout << content << std::endl;
        }
        
        file.close();
    }
    
    return 0;
}

5. 二进制文件操作

cpp 复制代码
#include <fstream>
#include <iostream>

struct Data {
    int id;
    double value;
    char name[20];
};

int main() {
    // 写入二进制数据
    Data data = {1, 3.14, "Test"};
    
    std::ofstream outFile("binary.dat", std::ios::binary);
    if (outFile) {
        outFile.write(reinterpret_cast<char*>(&data), sizeof(Data));
        outFile.close();
    }
    
    // 读取二进制数据
    Data readData;
    std::ifstream inFile("binary.dat", std::ios::binary);
    if (inFile) {
        inFile.read(reinterpret_cast<char*>(&readData), sizeof(Data));
        std::cout << "ID: " << readData.id 
                  << ", Value: " << readData.value 
                  << ", Name: " << readData.name << std::endl;
        inFile.close();
    }
    
    return 0;
}

6. 文件打开模式

模式标志 描述
std::ios::in 打开用于读取
std::ios::out 打开用于写入
std::ios::app 追加模式(在文件末尾写入)
std::ios::ate 打开后定位到文件末尾
std::ios::trunc 如果文件存在,先截断
std::ios::binary 二进制模式

重要提示

  1. 总是检查文件是否成功打开
  2. 记得关闭文件(虽然析构函数会自动关闭,但显式关闭是好习惯)
  3. 处理可能的异常(文件不存在、权限问题等)
  4. 使用合适的打开模式
  5. 二进制文件操作时要注意数据对齐和字节顺序

这些是 C++ 中文件操作的基本方法,根据具体需求选择合适的方式。

相关推荐
无忧.芙桃5 小时前
C++语言原理与实践(二十三):哈希表的实现
c++·链表·哈希算法·散列表·哈希表
AvocadoZeroOneOI8 小时前
B4500 [GESP202603 三级] 凯撒密码 详细解题报告
c++·算法
whitelbwwww10 小时前
cuBLAS--CUDA高性能线性代数计算库--第一部分
c++·线性代数·gpu算力·cuda c++
eggwyw13 小时前
C++设计模式之解释器模式
开发语言·c++
我不会插花弄玉1 天前
13.多路转接epoll【由浅入深-网络】
网络·c++·epoll
郝学胜-神的一滴1 天前
Effective STL 条款03:容器中的对象复制要廉价且正确
开发语言·数据结构·c++·算法·rpc·stl
西西弗Sisyphus1 天前
C++ explicit 关键字工程实践
开发语言·c++
AIgorithmGEEK1 天前
std::unordered_map 与 std::unordered_set:接口、算法技巧与权衡 (速查)
c++·算法·哈希表·负载因子·桶·unordered_map·unordered_set
一拳一个呆瓜1 天前
【STL】头文件:<cmath>
c++·stl
草莓熊Lotso1 天前
【C++ 基于微服务的即时通讯系统】ElasticSearch 用户数据管理实现
linux·数据库·c++·elasticsearch·微服务·架构