C++学习系列(14):C++ 文件操作(文件读写、流操作)
1. 引言
在 C++ 中,文件操作是程序与外部数据交互的核心部分。C++ 提供了 <fstream> 头文件,支持:
- 文本文件(txt)读写
- 二进制文件(bin)读写
- 文件流 (
ifstream、ofstream、fstream)
本篇博客将详细介绍 C++ 文件操作,包括:
- 文件流的基本概念
- 文本文件的读写
- 二进制文件的读写
- 文件指针定位
- 文件异常处理
2. C++ 文件流概述
C++ 通过 <fstream> 提供 三种文件流类:
| 文件流 | 作用 |
|---|---|
ifstream | 文件输入流(读取) |
ofstream | 文件输出流(写入) |
fstream | 文件读写流(同时读写) |
📌 示例
#include <fstream>
#include <iostream>
int main() {
std::ofstream file("example.txt"); // 创建文件
file << "Hello, C++ 文件操作!"; // 写入内容
file.close(); // 关闭文件
}
✅ ofstream 负责写入文件
3. 文本文件操作
3.1 写入文本文件
使用 ofstream 写入文件:
#include <fstream>
#include <iostream>
int main() {
std::ofstream outFile("data.txt"); // 创建文件
if (!outFile) {
std::cerr << "文件打开失败!\n";
return 1;
}
outFile << "C++ 文件操作示例\n";
outFile << "Hello, World!\n";
outFile.close(); // 关闭文件
return 0;
}
📌 解析
std::ofstream outFile("data.txt");✅ 创建并打开文件outFile << "Hello, World!\n";✅ 向文件写入内容outFile.close();✅ 关闭文件
3.2 读取文本文件
使用 ifstream 读取文件内容:
#include <fstream>
#include <iostream>
#include <string>
int main() {
std::ifstream inFile("data.txt"); // 读取文件
if (!inFile) {
std::cerr << "文件打开失败!\n";
return 1;
}
std::string line;
while (std::getline(inFile, line)) { // 逐行读取
std::cout << line << std::endl;
}
inFile.close(); // 关闭文件
return 0;
}
✅ std::getline(inFile, line) 逐行读取文件
4. 二进制文件操作
4.1 写入二进制文件
#include <fstream>
#include <iostream>
struct Data {
int id;
double value;
};
int main() {
std::ofstream outFile("data.bin", std::ios::binary);
Data d = {1, 99.99};
outFile.write(reinterpret_cast<char*>(&d), sizeof(Data)); // 写入二进制数据
outFile.close();
return 0;
}
📌 解析
std::ios::binary✅ 以二进制模式打开reinterpret_cast<char*>(&d)✅ 转换数据类型进行存储outFile.write()✅ 写入二进制数据
4.2 读取二进制文件
#include <fstream>
#include <iostream>
struct Data {
int id;
double value;
};
int main() {
std::ifstream inFile("data.bin", std::ios::binary);
Data d;
inFile.read(reinterpret_cast<char*>(&d), sizeof(Data)); // 读取数据
std::cout << "ID: " << d.id << ", Value: " << d.value << std::endl;
inFile.close();
return 0;
}
✅ 使用 inFile.read() 读取二进制数据
5. 文件指针操作
C++ 提供 seekg() 和 seekp() 控制文件指针位置:
| 方法 | 作用 |
|---|---|
seekg(offset, dir) | 设置输入流指针 |
seekp(offset, dir) | 设置输出流指针 |
tellg() | 获取当前读指针位置 |
tellp() | 获取当前写指针位置 |
📌 示例
#include <fstream>
#include <iostream>
int main() {
std::ofstream file("example.txt");
file << "Hello, C++!";
file.seekp(7); // 将写指针移动到第7个字符
file << "World!";
file.close();
}
✅ seekp(7) 移动写指针到第 7 个字符,修改内容
6. 文件异常处理
使用 fail() 检测文件错误:
std::ifstream file("not_exist.txt");
if (file.fail()) {
std::cerr << "文件打开失败!\n";
}
✅ fail() 监测文件是否打开失败
7. 总结
✅ ifstream 读取文件
✅ ofstream 写入文件
✅ fstream 同时读写
✅ 支持文本 & 二进制文件
✅ 支持文件指针操作
📢 下一篇 C++学习系列(15):C++ 智能指针(智能内存管理),敬请期待!🚀
💡 如果你喜欢这篇文章,欢迎点赞、收藏,并关注本系列!
1万+

被折叠的 条评论
为什么被折叠?



