文件操作
学习C++文件流和文件系统操作
70%
文件流基础
二进制文件
高级操作
文件流操作基础
文件的打开与关闭
使用文件流进行基本的文件读写操作。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
// 写入文件
ofstream outFile("example.txt");
if (outFile.is_open()) {
outFile << "Hello, World!" << endl;
outFile << "这是第二行" << endl;
outFile.close();
} else {
cerr << "无法打开文件!" << endl;
}
// 读取文件
ifstream inFile("example.txt");
if (inFile.is_open()) {
string line;
while (getline(inFile, line)) {
cout << line << endl;
}
inFile.close();
}
// 文件打开模式
ofstream outFile2("binary.dat", ios::binary | ios::out);
ifstream inFile2("text.txt", ios::in);
// 检查文件状态
if (inFile2.good()) {
cout << "文件状态正常" << endl;
}
if (inFile2.eof()) {
cout << "到达文件末尾" << endl;
}
if (inFile2.fail()) {
cout << "操作失败" << endl;
}
}
- ifstream:输入文件流,用于读取文件
- ofstream:输出文件流,用于写入文件
- fstream:同时支持读写操作
- 支持多种打开模式和状态检查