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

九、文件流状态检查

相关推荐
Cx330❀6 小时前
【MySQL基础】一文吃透“表的约束”:从 Null/Default 到主外键的终极安全法则
linux·服务器·数据库·c++·mysql·安全
c238566 小时前
第二篇:《测试指挥官:可视化单题自测框架(含 assert 实操)》
java·数据库·c++·算法·安全性测试
辞旧 lekkk6 小时前
【Redis初阶】常见数据类型
开发语言·数据库·c++·redis·学习·缓存·bootstrap
帅次7 小时前
Kotlin 与 Java 互操作:混合工程里的平台类型与 API 边界
java·开发语言·kotlin·suspend·nullable
dtq04248 小时前
C语言-结构体详解
c语言·开发语言·学习
梅雅达编程笔记9 小时前
编程启蒙|Scratch 转 Python 系列第9天:字典/哈希表积木双向对照(AI大模型参数配置表实战)
开发语言·人工智能·python·numpy·pandas
持力行9 小时前
C++与Java变量声明、定义及内存分配的核心区别
java·开发语言·c++
Rainy Blue8839 小时前
C转C++速成
c语言·c++·算法
txzrxz10 小时前
二分图详解
数据结构·c++·算法·图论·深度优先搜索·二分图染色
jinyishu_10 小时前
C++ 继承全解:从基础到高级特性
开发语言·c++