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;
}
相关推荐
贩卖纯净水.15 分钟前
webpack打包学习
前端·学习·webpack
崔高杰1 小时前
To be or Not to be, That‘s a Token——论文阅读笔记——Beyond the 80/20 Rule和R2R
论文阅读·笔记
咒法师无翅鱼1 小时前
【个人笔记】数据库原理(西电)
笔记
yxc_inspire1 小时前
基于Qt的app开发第十三天
c++·qt·app·tcp·面向对象
虾球xz2 小时前
CppCon 2015 学习:Concurrency TS Editor’s Report
开发语言·c++·学习
Moonnnn.2 小时前
【电赛培训课程】运算放大器及其应用电路设计
笔记·学习
潇-xiao2 小时前
Qt 按钮类控件(Push Button 与 Radio Button)(1)
c++·qt
板鸭〈小号〉2 小时前
命名管道实现本地通信
开发语言·c++
pop_xiaoli3 小时前
UI学习—cell的复用和自定义cell
学习·ui·ios
rui锐rui3 小时前
大模型学习
学习