C++ 文件操作教程:打开、读写、关闭与状态检测
C++ 提供多种对文件进行操作的方式,包括:
-
以文本或二进制方式打开文件:通过 fstream 库中的 ifstream(输入文件流)和 ofstream(输出文件流)类以文本或二进制方式打开文件,并进行读写操作。
-
读写文件内容:使用输入文件流对象和输出文件流对象的相关方法,如 getline(), read(), write() 等方法对文件进行读取和写入。
-
文件位置指针:使用文件位置指针控制读写位置,如 seekg() 和 seekp() 方法。
-
文件状态检测:使用文件流对象的相关方法,如 eof(), bad(), fail() 等方法检测文件状态。
-
关闭文件:使用文件流对象的 close() 方法关闭文件。
以下是一个简单的示例代码,展示了如何以文本方式打开文件,并进行读写操作:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// 打开文件
ofstream outfile;
outfile.open('example.txt');
if (!outfile) {
cout << '文件打开失败!' << endl;
return 0;
}
// 写入文件
outfile << 'Hello World!' << endl;
// 关闭文件
outfile.close();
// 重新打开文件
ifstream infile;
infile.open('example.txt');
if (!infile) {
cout << '文件打开失败!' << endl;
return 0;
}
// 读取文件
string content;
getline(infile, content);
cout << content << endl;
// 关闭文件
infile.close();
return 0;
}
原文地址: http://www.cveoy.top/t/topic/olhB 著作权归作者所有。请勿转载和采集!