C++学习笔记(二十一)——文件读写

一、文件读写

作用:

文件读写指的是将数据从程序存储到文件,或从文件读取数据 ,以实现数据的持久化存储

C++ 提供了 fstream 头文件,用于文件操作,主要包括:

  • ofstream(输出文件流)------ 向文件写入数据
  • ifstream(输入文件流)------ 从文件读取数据
  • fstream(文件流)------ 同时支持读写

应用场景:

  • 配置文件(保存程序设置)
  • 日志系统(记录程序运行状态)
  • 数据存储(存储用户数据、序列化对象)

二、C++ 文件操作库

头文件#include <fstream>

(1)主要类:

作用
ofstream 写文件
ifstream 读文件
fstream 读写文件

(2)文件打开模式(open()mode 参数)

模式 作用
ios::in 只读方式打开文件(文件必须存在)
ios::out 写入方式打开文件(文件不存在会创建,存在则清空)
ios::app 追加方式打开文件(数据追加到文件末尾)
ios::binary 二进制模式打开文件
ios::ate 打开文件并移动到文件末尾
ios::trunc 清空文件内容(默认行为)

(3)文件读写方法

操作 方法
写入文件 ofstream <<write()
读取文件 ifstream >>getline()read()
读写文件 fstream <<>>seekg()
文本文件 ifstream/ofstream 逐行读写
二进制文件 ifstream/ofstream + ios::binary write()read()

注意:

  • 文本文件: getline() 逐行读取;
  • 二进制文件: read()/write() 提高性能;
  • fstream 用于同时读写,避免频繁打开关闭文件。

(4)文件状态检查函数

文件状态检查函数,返回值是一个布尔值

函数名 作用
good() 文件流是否处于正常状态,没有遇到任何错误或异常
fail() 是否发生格式错误或输入/输出操作失败(但不包括 badbit)
eof() 是否读取操作到达文件末尾
bad() 是否发生了严重错误,如磁盘损坏、系统错误等

三、写入文件(ofstream

示例1------向文件写入数据

cpp 复制代码
#include <iostream>
using namespace std;
#include <fstream>

int main() {
    ofstream outFile("test.txt");  // 创建并打开文件

    if (!outFile)
    {
        cout << "文件打开失败!" << endl;
        return -1;
    }

    outFile << "Hello, C++ 文件操作!" << endl;
    outFile << "写入第二行数据" << endl;
    outFile.close();  // 关闭文件

    cout << "数据已写入 test.txt" << endl;

    system("pause");
    return 0;
}

注意:

  • ofstream outFile("test.txt"):创建/打开 test.txt,默认清空文件
  • outFile << "内容"向文件写入数据
  • outFile.close()关闭文件,释放资源。

示例2------追加模式写入文件

cpp 复制代码
#include <iostream>
using namespace std;
#include <fstream>

int main() {
    ofstream outFile("test.txt", ios::app);  // 追加模式

    outFile << "追加数据 1" << endl;
    outFile << "追加数据 2" << endl;

    outFile.close();

    system("pause");
    return 0;
}

注意:

  • ios::app 追加模式 ,不会清空文件,而是在末尾追加数据

四、 读取文件(ifstream

示例1------逐行读取文件

cpp 复制代码
#include <iostream>
using namespace std;
#include <fstream>
#include <string>

int main() {
    ifstream inFile("test.txt");  // 打开文件

    if (!inFile)
    {
        cout << "文件打开失败!" << endl;
        return -1;
    }

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

    inFile.close(); // 关闭文件

    system("pause");
    return 0;
}

注意:

  • getline(inFile, line) 逐行读取文件内容 ,存入 line 变量。

示例2------逐个字符读取文件

cpp 复制代码
#include <iostream>
using namespace std;
#include <fstream>

int main() {
    ifstream inFile("test.txt"); // 打开文件

    if (!inFile)
    {
        cout << "文件打开失败!" << endl;
        return -1;
    }

    char ch;
    while (inFile.get(ch)) // 逐个字符读取
    {
        cout << ch;
    }

    inFile.close(); // 关闭文件

    system("pause");
    return 0;
}

注意:

  • 适用于逐个字符解析文件 ,如读取二进制文件处理格式化文本

五、读写文件(fstream

示例------同时读写文件

cpp 复制代码
#include <iostream>
using namespace std;
#include <fstream>
#include <string>

int main() {
    fstream file("data.txt", ios::in | ios::out | ios::app);  // 读写+追加

    if (!file)
    {
        cout << "文件打开失败!" << endl;
        return -1;
    }

    file << "新数据写入" << endl;

    file.seekg(0);  // 移动到文件开头
    string line;
    while (getline(file, line))
    {
        cout << line << endl;
    }

    file.close(); // 关闭文件

    system("pause");
    return 0;
}

注意:

  • fstream 同时支持读写ios::in | ios::out 使得文件可读可写。
  • seekg(0)读指针移到文件开头,确保读取最新内容。

六、特殊用法

(1)处理二进制文件

示例1------写入二进制文件

cpp 复制代码
#include <iostream>
using namespace std;
#include <fstream>

struct Person 
{
    char name[20];
    int age;
};

int main() {
    ofstream outFile("person.dat", ios::binary); // 创建并打开二进制文件

    Person p1 = { "Alice", 25};
    outFile.write(reinterpret_cast<char*>(&p1), sizeof(p1));  // 写入二进制数据

    outFile.close(); // 关闭文件

    system("pause");
    return 0;
}

注意:

  • ios::binary 以二进制模式打开文件
  • write(reinterpret_cast<char*>(&p1), sizeof(p1)) 将结构体写入文件

示例2------读取二进制文件

cpp 复制代码
#include <iostream>
using namespace std;
#include <fstream>

struct Person
{
    char name[20];
    int age;
};

int main() {
    ifstream inFile("person.dat", ios::binary); // 打开二进制文件

    Person p;
    inFile.read(reinterpret_cast<char*>(&p), sizeof(p));  // 读取二进制数据

    cout << "姓名: " << p.name << ", 年龄: " << p.age << endl;
    inFile.close(); // 关闭文件

    system("pause");
    return 0;
}

注意:

  • 适用于存储复杂数据结构 (如 struct)。
  • 文件大小更小,读取速度更快

(2) 检查文件流的状态

作用:
good() 是 C++ 中std::ifstreamstd::ofstreamstd::fstream文件流类提供的成员函数之一 。它可以检查文件流的状态 ,判断是否处于"良好"状态,即文件流没有遇到任何错误或异常情况。

示例:

cpp 复制代码
#include <iostream>
using namespace std;
#include <fstream>

int main()
{
    ifstream file("test.txt");

    if (file.good())
    {
        cout << "文件可以正常读取!" << std::endl;
    }
    else
    {
        cout << "文件不可读!可能不存在或发生了错误!" << std::endl;
    }

    file.close(); // 关闭文件

    system("pause");
    return 0;
}

(3) 获取文件大小

作用:

  • tellg() 是 C++ 中 std::ifstream(输入文件流)的成员函数,用于获取当前文件读取位置的指针 (文件指针),即读取操作即将在文件中的哪个字节位置执行
  • tellg() 常与 seekg() 结合使用,以计算文件大小

示例:

cpp 复制代码
#include <iostream>
using namespace std;
#include <fstream>

struct Person
{
    char name[20];
    int age;
};

int main()
{
    ofstream outFile("person.dat", ios::binary); // 创建并打开二进制文件

    Person p1 = { "Alice", 25 };
    outFile.write(reinterpret_cast<char*>(&p1), sizeof(p1));  // 写入二进制数据

    outFile.close(); // 关闭文件

    ifstream file("person.dat", ios::binary); // 打开二进制文件

    file.seekg(0, ios::end);  // 将指针移动到文件末尾
    streampos fileSize = file.tellg();  // 获取当前位置,即文件大小
    cout << "文件大小: " << fileSize << " 字节" << std::endl;

    file.close();

    system("pause");
    return 0;
}
相关推荐
小坏坏的大世界1 小时前
C++ STL常用容器总结(vector, deque, list, map, set)
c++·算法
liulilittle2 小时前
C++ TAP(基于任务的异步编程模式)
服务器·开发语言·网络·c++·分布式·任务·tap
im_AMBER3 小时前
学习日志19 python
python·学习
励志要当大牛的小白菜4 小时前
ART配对软件使用
开发语言·c++·qt·算法
PAK向日葵5 小时前
【算法导论】如何攻克一道Hard难度的LeetCode题?以「寻找两个正序数组的中位数」为例
c++·算法·面试
_Kayo_7 小时前
VUE2 学习笔记6 vue数据监测原理
vue.js·笔记·学习
chenchihwen7 小时前
大模型应用班-第2课 DeepSeek使用与提示词工程课程重点 学习ollama 安装 用deepseek-r1:1.5b 分析PDF 内容
人工智能·学习
超浪的晨7 小时前
Java UDP 通信详解:从基础到实战,彻底掌握无连接网络编程
java·开发语言·后端·学习·个人开发
QQ_4376643149 小时前
C++11 右值引用 Lambda 表达式
java·开发语言·c++
使二颗心免于哀伤9 小时前
《设计模式之禅》笔记摘录 - 10.装饰模式
笔记·设计模式