C++文件操作

一、什么是文件流(File Stream)

在 C++ 中,文件操作通过 **流(Stream)**完成。

可以把流理解为:

程序 ↔ 数据通道 ↔ 文件

数据像水一样在流中流动。

C++ 文件流库:

#include

提供三个核心类:

类 作用

ifstream 读文件(input file stream)

ofstream 写文件(output file stream)

fstream 读写文件

二、文件流基本使用流程
1. 写文件示例

cpp 复制代码
#include <iostream>
#include <fstream>
using namespace std;
int main() {
    ofstream fout("data.txt");   // 打开文件
    fout << "Hello C++" << endl;
    fout << 100 << endl;
    fout.close();   // 关闭文件
    return 0;
}


2. 读文件示例

cpp 复制代码
#include <iostream>
#include <fstream>
using namespace std;
int main() {
    ifstream fin("data.txt");
    string str;
    int num;
    fin >> str >> str;  // 读 Hello C++
    fin >> num;
    cout << str << endl;
    cout << num << endl;
    fin.close();
}

三、文件打开方式(非常重要)

文件打开有不同模式:

ofstream fout("file.txt", ios::out);

四、文件是否成功打开

必须检查,否则程序可能崩溃。

cpp 复制代码
ifstream fin("data.txt");
if (!fin) {
    cout << "文件打开失败" << endl;
    return 1;
}*
或者
*if (fin.is_open()) {
    cout << "打开成功";
}

五、按行读取(最常用)

cpp 复制代码
string line;
while (getline(fin, line)) {
    cout << line << endl;
}

适用于:

文本处理

配置文件

日志分析

六、读到文件结束(EOF)

cpp 复制代码
while (!fin.eof()) {
    string str;
    fin >> str;
    cout << str << endl;
}

七、二进制文件操作(重点)

用于:

图像

音频

结构体保存

网络数据

1. 写二进制

cpp 复制代码
ofstream fout("data.bin", ios::binary);
int a = 100;
fout.write((char*)&a, sizeof(a));
fout.close();

2. 读二进制

cpp 复制代码
ifstream fin("data.bin", ios::binary);
int a;
fin.read((char*)&a, sizeof(a));
cout << a << endl;

3. 保存结构体

cpp 复制代码
struct Student {
    int id;
    char name[20];
};
Student s = {1, "Rui"};
ofstream fout("stu.bin", ios::binary);
fout.write((char*)&s, sizeof(s));
fout.close();

读取:

cpp 复制代码
Student s;
ifstream fin("stu.bin", ios::binary);
fin.read((char*)&s, sizeof(s));

八、文件指针操作(高级)

文件内部有两个指针:

  1. 移动读指针
cpp 复制代码
fin.seekg(10);  // 从头移动10字节
fin.seekg(-10, ios::end);  //从末尾
  1. 获取当前位置
cpp 复制代码
cout << fin.tellg() << endl;

写指针类似:

cpp 复制代码
fout.seekp();
fout.tellp();

九、文件流状态检查

相关推荐
overmind1 小时前
oeasy Python 114 在列表指定位置插入insert
开发语言·python
github.com/starRTC2 小时前
Claude Code中英文系列教程34:再谈Skills
开发语言·c#·ai编程
毕设源码-赖学姐2 小时前
【开题答辩全过程】以 基于Java的外卖点餐网站为例,包含答辩的问题和答案
java·开发语言
蜡笔羊驼2 小时前
LALIC环境安装过程
开发语言·python·深度学习
L_Aria2 小时前
3824. 【NOIP2014模拟9.9】渴
c++·算法·图论
codeJinger2 小时前
【Python】基础知识
开发语言·python
lsx2024062 小时前
JavaScript Math(算数)详解
开发语言
csbysj20202 小时前
Debian Docker 安装指南
开发语言
ShineWinsu2 小时前
对于模拟实现C++list类的详细解析—上
开发语言·数据结构·c++·算法·面试·stl·list