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

九、文件流状态检查

相关推荐
xlp666hub9 小时前
Leetcode 第三题:用C++解决最长连续序列
c++·leetcode
会员源码网10 小时前
构造函数抛出异常:C++对象部分初始化的陷阱与应对策略
c++
xlp666hub12 小时前
Leetcode第二题:用 C++ 解决字母异位词分组
c++·leetcode
不想写代码的星星13 小时前
static 关键字:从 C 到 C++,一篇文章彻底搞懂它的“七十二变”
c++
xlp666hub1 天前
Leetcode第一题:用C++解决两数之和问题
c++·leetcode
不想写代码的星星2 天前
C++继承、组合、聚合:选错了是屎山,选对了是神器
c++
不想写代码的星星3 天前
std::function 详解:用法、原理与现代 C++ 最佳实践
c++
樱木Plus4 天前
深拷贝(Deep Copy)和浅拷贝(Shallow Copy)
c++
blasit6 天前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
肆忆_7 天前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++