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();

九、文件流状态检查

相关推荐
咸鱼2.01 小时前
【java入门到放弃】跨域
java·开发语言
skiy2 小时前
java与mysql连接 使用mysql-connector-java连接msql
java·开发语言·mysql
一念春风2 小时前
智能文字识别工具(AI)
开发语言·c#·wpf
桦02 小时前
【C++复习】:继承
开发语言·c++
何仙鸟2 小时前
GarmageSet下载和处理
java·开发语言
鱼难终2 小时前
类和对象(下)
c++
wefly20173 小时前
免安装!m3u8live.cn在线 M3U8 播放器,小白也能快速上手
java·开发语言·python·json·php·m3u8·m3u8在线转换
云泽8083 小时前
深入 AVL 树:原理剖析、旋转算法与性能评估
数据结构·c++·算法
薛先生_0993 小时前
js学习语法第一天
开发语言·javascript·学习
报错小能手3 小时前
深入理解 Linux 虚拟内存管理
开发语言·操作系统