C++文件与流操作完全指南
编程小白也能理解的C++文件操作知识
深入浅出讲解文件读写、流操作、二进制处理等核心概念
📁 文件流基础
什么是文件流?
文件流是C++中处理文件输入输出的机制,就像水流一样,数据可以从程序流向文件(输出),也可以从文件流向程序(输入)。
三种文件流类
- ifstream – 输入文件流(用于读取文件)
- ofstream – 输出文件流(用于写入文件)
- fstream – 文件流(可同时读写)
// 包含文件流头文件
#include <fstream>
// 创建文件流对象
ifstream inputFile; // 用于读取文件
ofstream outputFile; // 用于写入文件
fstream file; // 可用于读写
#include <fstream>
// 创建文件流对象
ifstream inputFile; // 用于读取文件
ofstream outputFile; // 用于写入文件
fstream file; // 可用于读写
🔓 文件打开与关闭
打开文件
使用open()
方法打开文件,需要指定文件名和打开模式:
// 打开文件的基本语法
fileStream.open(“filename”, mode);
fileStream.open(“filename”, mode);
常用打开模式
ios::in
– 打开文件用于读取ios::out
– 打开文件用于写入ios::app
– 追加模式(在文件末尾添加)ios::trunc
– 如果文件存在,先清空内容ios::binary
– 以二进制模式打开
关闭文件
使用close()
方法关闭文件:
fileStream.close();
小贴士: 当文件流对象超出作用域时,会自动关闭文件。但显式关闭文件是良好的编程习惯!
📝 文本文件操作
写入文本文件
使用<<
运算符(就像cout
一样):
ofstream outFile;
outFile.open(“example.txt”);
outFile << “Hello, World!” << endl;
outFile << “This is a text file.” << endl;
outFile.close();
outFile.open(“example.txt”);
outFile << “Hello, World!” << endl;
outFile << “This is a text file.” << endl;
outFile.close();
读取文本文件
使用>>
运算符读取单词,或使用getline()
读取整行:
ifstream inFile;
inFile.open(“example.txt”);
// 逐词读取
string word;
while (inFile >> word) {
cout << word << endl;
}
// 逐行读取
string line;
while (getline(inFile, line)) {
cout << line << endl;
}
inFile.close();
inFile.open(“example.txt”);
// 逐词读取
string word;
while (inFile >> word) {
cout << word << endl;
}
// 逐行读取
string line;
while (getline(inFile, line)) {
cout << line << endl;
}
inFile.close();
📄 文本文件操作
文本文件是人类可读的文件,以ASCII或Unicode编码存储数据。
特点:
- 内容是人类可读的字符
- 使用
<<
和>>
运算符读写 - 自动处理字符编码和换行符转换
- 适合存储配置、日志、简单数据
示例代码:写入文本
ofstream textFile(“data.txt”);
textFile << “Name: John Doe” << endl;
textFile << “Age: 30” << endl;
textFile << “Score: 95.5” << endl;
textFile.close();
textFile << “Name: John Doe” << endl;
textFile << “Age: 30” << endl;
textFile << “Score: 95.5” << endl;
textFile.close();
🔢 二进制文件操作
二进制文件直接存储数据的原始字节形式,不是为人类阅读设计的。
特点:
- 存储原始字节数据
- 使用
read()
和write()
方法 - 没有字符转换,保留数据的精确表示
- 适合存储图像、音频、视频或复杂数据结构
示例代码:写入二进制
struct Person {
char name[50];
int age;
double score;
};
Person p = {“Alice”, 25, 88.5};
ofstream binFile(“data.bin”, ios::binary);
binFile.write((char*)&p, sizeof(p));
binFile.close();
char name[50];
int age;
double score;
};
Person p = {“Alice”, 25, 88.5};
ofstream binFile(“data.bin”, ios::binary);
binFile.write((char*)&p, sizeof(p));
binFile.close();
📍 文件位置指针
文件位置指针就像书签一样,标记着文件中当前读写的位置。
常用函数
seekg()
– 设置输入位置指针seekp()
– 设置输出位置指针tellg()
– 获取输入位置指针tellp()
– 获取输出位置指针
偏移参考位置
ios::beg
– 文件开头ios::cur
– 当前位置ios::end
– 文件末尾
// 将读指针移动到文件开头后100字节
inFile.seekg(100, ios::beg);
// 将写指针移动到文件末尾
outFile.seekp(0, ios::end);
// 获取当前读指针位置
streampos pos = inFile.tellg();
inFile.seekg(100, ios::beg);
// 将写指针移动到文件末尾
outFile.seekp(0, ios::end);
// 获取当前读指针位置
streampos pos = inFile.tellg();
⚠️ 错误处理
文件操作可能会出错,良好的错误处理是必不可少的!
检查文件是否打开成功
ifstream file(“data.txt”);
if (!file.is_open()) {
cerr << “无法打开文件!” << endl;
return 1;
}
if (!file.is_open()) {
cerr << “无法打开文件!” << endl;
return 1;
}
检查文件状态
good()
– 一切正常eof()
– 到达文件末尾fail()
– 操作失败(如类型不匹配)bad()
– 发生严重错误
while (file.good()) {
// 读取文件内容
}
if (file.eof()) {
cout << “已到达文件末尾” << endl;
}
else if (file.fail()) {
cout << “非EOF错误” << endl;
}
// 读取文件内容
}
if (file.eof()) {
cout << “已到达文件末尾” << endl;
}
else if (file.fail()) {
cout << “非EOF错误” << endl;
}
💻 完整示例
文件复制程序
#include <fstream>
#include <iostream>
using namespace std;
int main() {
// 打开源文件
ifstream source(“source.txt”, ios::binary);
if (!source) {
cerr << “无法打开源文件!” << endl;
return 1;
}
// 创建目标文件
ofstream dest(“destination.txt”, ios::binary);
if (!dest) {
cerr << “无法创建目标文件!” << endl;
return 1;
}
// 逐字节复制
char ch;
while (source.get(ch)) {
dest.put(ch);
}
// 检查复制是否成功
if (!source.eof() || !dest) {
cerr << “复制过程中出错!” << endl;
return 1;
}
cout << “文件复制成功!” << endl;
source.close();
dest.close();
return 0;
}
#include <iostream>
using namespace std;
int main() {
// 打开源文件
ifstream source(“source.txt”, ios::binary);
if (!source) {
cerr << “无法打开源文件!” << endl;
return 1;
}
// 创建目标文件
ofstream dest(“destination.txt”, ios::binary);
if (!dest) {
cerr << “无法创建目标文件!” << endl;
return 1;
}
// 逐字节复制
char ch;
while (source.get(ch)) {
dest.put(ch);
}
// 检查复制是否成功
if (!source.eof() || !dest) {
cerr << “复制过程中出错!” << endl;
return 1;
}
cout << “文件复制成功!” << endl;
source.close();
dest.close();
return 0;
}