📁 C++ 文件操作 - L24 进阶概念

掌握文件读写、文本和二进制文件处理、异常处理

📚 文件操作概述

为什么需要文件操作?

程序运行时数据存储在内存中,程序结束后数据会丢失。文件操作可以将数据持久化保存到磁盘,实现数据的长期存储。

  • 数据持久化:保存用户数据、配置信息
  • 数据共享:不同程序之间交换数据
  • 大数据处理:处理超出内存容量的数据
  • 日志记录:记录程序运行状态和错误信息
  • 数据备份:重要数据的备份和恢复
💡 文件类型:
文本文件:以ASCII码存储,人类可读(如.txt、.csv)
二进制文件:以二进制格式存储,效率高(如.dat、.bin)

C++文件操作的核心类

#include <iostream> #include <fstream> // 文件操作头文件 using namespace std; int main() { // 三个核心类: // ofstream - 输出文件流(写文件) // ifstream - 输入文件流(读文件) // fstream - 文件流(读写文件) // 示例:创建输出文件流对象 ofstream outFile; // 示例:创建输入文件流对象 ifstream inFile; // 示例:创建读写文件流对象 fstream file; return 0; }

文件打开模式

#include <iostream> #include <fstream> using namespace std; int main() { // 常用打开模式: // ios::in - 读取模式 // ios::out - 写入模式(默认,会清空文件) // ios::app - 追加模式(在文件末尾添加) // ios::ate - 打开后定位到文件末尾 // ios::trunc - 如果文件存在则清空(与out一起使用) // ios::binary - 二进制模式 // 示例1:写入文件(覆盖模式) ofstream out1("test.txt", ios::out); // 示例2:追加到文件 ofstream out2("test.txt", ios::app); // 示例3:读取文件 ifstream in("test.txt", ios::in); // 示例4:读写二进制文件 fstream bin("data.bin", ios::in | ios::out | ios::binary); return 0; }

⚙️ 文件基本操作

写入文本文件

#include <iostream> #include <fstream> using namespace std; int main() { // 方法1:构造函数直接打开 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; } // 方法1:逐行读取 string line; cout << "=== 逐行读取 ===" << endl; while (getline(inFile, line)) { cout << line << endl; } // 重置文件指针到开头 inFile.clear(); inFile.seekg(0, ios::beg); // 方法2:逐个单词读取 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() { // 使用ios::app模式,在文件末尾追加内容 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); // seekg():移动读取指针 // seekp():移动写入指针 // 移动到文件开头 file.seekg(0, ios::beg); // 移动到文件末尾 file.seekg(0, ios::end); // 从当前位置向前移动10个字节 file.seekg(-10, ios::cur); // tellg():获取当前读取位置 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"; // write():写入二进制数据 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]; // read():读取二进制数据 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; // 写入CSV文件 void writeCSV(const string& filename) { ofstream outFile(filename); // 写入表头 outFile << "姓名,年龄,成绩" << endl; // 写入数据 outFile << "张三,18,90" << endl; outFile << "李四,19,85" << endl; outFile << "王五,20,92" << endl; outFile.close(); } // 读取CSV文件 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. 数据保存到文件中,程序重启后仍然可用

点击"生成代码框架"查看提示...