📚 文件操作概述
为什么需要文件操作?
程序运行时数据存储在内存中,程序结束后数据会丢失。文件操作可以将数据持久化保存到磁盘,实现数据的长期存储。
- ✅ 数据持久化:保存用户数据、配置信息
- ✅ 数据共享:不同程序之间交换数据
- ✅ 大数据处理:处理超出内存容量的数据
- ✅ 日志记录:记录程序运行状态和错误信息
- ✅ 数据备份:重要数据的备份和恢复
💡 文件类型:
• 文本文件:以ASCII码存储,人类可读(如.txt、.csv)
• 二进制文件:以二进制格式存储,效率高(如.dat、.bin)
C++文件操作的核心类
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream outFile;
ifstream inFile;
fstream file;
return 0;
}
文件打开模式
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream out1("test.txt", ios::out);
ofstream out2("test.txt", ios::app);
ifstream in("test.txt", ios::in);
fstream bin("data.bin", ios::in | ios::out | ios::binary);
return 0;
}
⚙️ 文件基本操作
写入文本文件
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream outFile("hello.txt");
if (!outFile.is_open()) {
cerr << "无法打开文件!" << endl;
return 1;
}
outFile << "Hello, File!" << endl;
outFile << "这是第二行" << endl;
outFile << 123 << " " << 45.67 << endl;
outFile.close();
cout << "文件写入成功!" << endl;
return 0;
}
读取文本文件
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream inFile("hello.txt");
if (!inFile.is_open()) {
cerr << "无法打开文件!" << endl;
return 1;
}
string line;
cout << "=== 逐行读取 ===" << endl;
while (getline(inFile, line)) {
cout << line << endl;
}
inFile.clear();
inFile.seekg(0, ios::beg);
cout << "\n=== 逐词读取 ===" << endl;
string word;
while (inFile >> word) {
cout << word << " ";
}
cout << endl;
inFile.close();
return 0;
}
追加模式写入
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream outFile("log.txt", ios::app);
if (!outFile.is_open()) {
cerr << "无法打开文件!" << endl;
return 1;
}
outFile << "[2024-01-01] 程序启动" << endl;
outFile << "[2024-01-01] 执行任务A" << endl;
outFile << "[2024-01-01] 程序结束" << endl;
outFile.close();
cout << "日志已追加!" << endl;
return 0;
}
🎮 互动实验:文件操作演示
模拟文件的写入和读取过程
输入内容后点击按钮...
🛠️ 常用文件方法
文件状态检查
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream inFile("test.txt");
if (inFile.is_open()) {
cout << "文件已打开" << endl;
}
if (inFile.eof()) {
cout << "已到达文件末尾" << endl;
}
if (inFile.fail()) {
cout << "读取失败" << endl;
}
if (inFile.good()) {
cout << "文件状态良好" << endl;
}
inFile.seekg(0, ios::end);
int size = inFile.tellg();
cout << "文件大小:" << size << " 字节" << endl;
inFile.close();
return 0;
}
文件指针操作
#include <iostream>
#include <fstream>
using namespace std;
int main() {
fstream file("test.txt", ios::in | ios::out);
file.seekg(0, ios::beg);
file.seekg(0, ios::end);
file.seekg(-10, ios::cur);
int pos = file.tellg();
cout << "当前位置:" << pos << endl;
file.close();
return 0;
}
二进制文件操作
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream outFile("data.bin", ios::binary);
int num = 12345;
double pi = 3.14159;
char str[] = "Hello";
outFile.write((char*)&num, sizeof(num));
outFile.write((char*)&pi, sizeof(pi));
outFile.write(str, sizeof(str));
outFile.close();
ifstream inFile("data.bin", ios::binary);
int readNum;
double readPi;
char readStr[10];
inFile.read((char*)&readNum, sizeof(readNum));
inFile.read((char*)&readPi, sizeof(readPi));
inFile.read(readStr, sizeof(readStr));
cout << "数字:" << readNum << endl;
cout << "PI:" << readPi << endl;
cout << "字符串:" << readStr << endl;
inFile.close();
return 0;
}
🚀 高级文件处理
异常处理
#include <iostream>
#include <fstream>
#include <stdexcept>
using namespace std;
void safeWriteFile(const string& filename, const string& content) {
ofstream outFile(filename);
if (!outFile.is_open()) {
throw runtime_error("无法打开文件:" + filename);
}
outFile << content;
if (outFile.fail()) {
throw runtime_error("写入文件失败");
}
outFile.close();
}
int main() {
try {
safeWriteFile("test.txt", "Hello, World!");
cout << "写入成功!" << endl;
} catch (const exception& e) {
cerr << "错误:" << e.what() << endl;
}
return 0;
}
实际应用:学生成绩管理
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
struct Student {
string name;
int score;
};
void saveStudents(const vector<Student>& students, const string& filename) {
ofstream outFile(filename);
for (const auto& s : students) {
outFile << s.name << " " << s.score << endl;
}
outFile.close();
}
vector<Student> loadStudents(const string& filename) {
vector<Student> students;
ifstream inFile(filename);
string name;
int score;
while (inFile >> name >> score) {
students.push_back({name, score});
}
inFile.close();
return students;
}
int main() {
vector<Student> students = {
{"张三", 90},
{"李四", 85},
{"王五", 92}
};
saveStudents(students, "students.txt");
cout << "数据已保存!" << endl;
vector<Student> loaded = loadStudents("students.txt");
cout << "\n读取的数据:" << endl;
for (const auto& s : loaded) {
cout << s.name << ": " << s.score << endl;
}
return 0;
}
CSV文件处理
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
using namespace std;
void writeCSV(const string& filename) {
ofstream outFile(filename);
outFile << "姓名,年龄,成绩" << endl;
outFile << "张三,18,90" << endl;
outFile << "李四,19,85" << endl;
outFile << "王五,20,92" << endl;
outFile.close();
}
void readCSV(const string& filename) {
ifstream inFile(filename);
string line;
getline(inFile, line);
cout << "姓名\t年龄\t成绩" << endl;
cout << "------------------------" << endl;
while (getline(inFile, line)) {
stringstream ss(line);
string name, age, score;
getline(ss, name, ',');
getline(ss, age, ',');
getline(ss, score, ',');
cout << name << "\t" << age << "\t" << score << endl;
}
inFile.close();
}
int main() {
writeCSV("data.csv");
cout << "CSV文件已创建!" << endl;
cout << "\n读取CSV文件:" << endl;
readCSV("data.csv");
return 0;
}
📝 实战练习
📝 理解测试
以下代码的作用是什么?
#include <fstream>
using namespace std;
int main() {
ofstream file("test.txt", ios::app);
file << "New Line" << endl;
file.close();
return 0;
}
选择答案查看解析...
💻 综合挑战
题目:编写一个程序,实现简单的日记本功能:
1. 可以添加新的日记条目(包含日期和内容)
2. 可以查看所有日记
3. 数据保存到文件中,程序重启后仍然可用
点击"生成代码框架"查看提示...