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;
}
相关推荐
red_redemption2 分钟前
自由学习记录(214)
学习
疯狂打码的少年31 分钟前
【数据结构】树的基本概念与二叉树定义
java·数据结构·笔记·算法
马上去吃汉堡王33 分钟前
Windows11安装Geant4
笔记
气泡水。35 分钟前
RHCSA笔记实记
linux·笔记
祈禾2 小时前
Redis三大特殊数据类型
运维·服务器·数据库·redis·笔记·缓存
祈禾2 小时前
计算机组成原理之编译、汇编、链接、解释
开发语言·汇编·笔记·学习
知识分享小能手2 小时前
线性代数学习教程,从入门到精通,矩阵的初等变换与线性方程组(6)
学习·线性代数·矩阵
小龙报2 小时前
【优选算法】1.搜索插入位置 2.x的平方根
java·c语言·数据结构·c++·python·算法·蓝桥杯
A_humble_scholar2 小时前
Linux(二) C++ TCP/UDP网络编程
linux·网络·c++
我命由我123453 小时前
四流一致(合同流、业务流、资金流、发票流)
经验分享·学习·职场和发展·求职招聘·职场发展·产品经理·学习方法