在C++中,文件操作函数主要包括ifstream
、ofstream
、fstream
等类,它们分别用于输入、输出和读写操作。下面是几个常用的文件操作函数:
open()
:打开文件,可以设置文件的打开方式、打开模式和文件名。打开方式包括in(输入)和out(输出),打开模式包括app(追加)、trunc(截断)、ate(文件结尾)等。
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream ofs("test.txt", ios::out | ios::app); //以追加的方式打开文件test.txt
if (!ofs) {
cerr << "Fail to open file!" << endl;
exit(1);
}
ofs << "Hello, world!" << endl; //将字符串写入文件
ofs.close(); //关闭文件
return 0;
}
2.close()
:关闭文件。
ofs.close();
3. is_open()
:判断文件是否打开成功。
if (!ofs.is_open()) {
cerr << "Fail to open file!" << endl;
exit(1);
}
4. getline()
:从文件中读取一行字符串。
string line;
while (getline(ifs, line)) {
cout << line << endl;
}
5. eof()
:判断文件是否到达结尾。
while (!ifs.eof()) {
getline(ifs, line);
cout << line << endl;
}
6. tellg()
和seekg()
:获取或设置文件指针的位置。
long pos = ifs.tellg(); //获取文件指针的位置
ifs.seekg(0, ios::beg); //设置文件指针的位置到文件开头
7. read()
和write()
:从文件中读取或写入一定数量的字节。
char buffer[1024];
ifs.read(buffer, sizeof(buffer)); //从文件中读取1024个字节
ofs.write(buffer, sizeof(buffer)); //将1024个字节写入文件