以前读写文件一般使用的是Qt的QFile类,不过这次因为这个软件需要比较小巧,使用Qt就不算方便了,因为使用Qt的话,在打包的时候会链接上各种东西。
因此,最后决定直接使用C++的fstream类进行读写(至于为什么不适用C的方式,主要原因在于C++在这方面控制的要比C好)。
示例代码如下:
void readFile(const string& fileName)
{
fstream file(fileName, ios::in);
if (!file.is_open())
{
cerr << fileName << " open failed." << endl;
return;
}
while (!file.eof())
{
char buffer[1024]{ 0 };
file.getLine(buffer, 1024);
cout << buffer << endl;
}
file.close();
}
void writeFile(const string& fileName, const vector<string> &data)
{
fstream file(fileName, ios::out);//ios::out默认打开之后清空文件
if (!file.is_open())
{
cerr << fileName << " open failed." << endl;
return;
}
for (const auto& str : data)
{
file << str << endl;//注意fstream的本质是一个“流”
}
file.close();
}
这里面着重想要强调的一点是,fstream的本质是一个“流”,因此要熟悉对于流的操作。