【发布时间】:2021-11-29 01:51:09
【问题描述】:
我想使用 C++ 使用 fstreams 写入大文件的开头。
我想出的方法是将整个数据写入一个临时文件,然后写入原始文件,然后将数据从tmp文件复制到原始文件中。
我想创建一个缓冲区,它将数据从原始文件传输到 tmp 文件,反之亦然。
该过程适用于所有人string、ostringstream 和stringstream。我希望数据的复制速度快,而且内存消耗最少。
示例与string:
void write(std::string& data)
{
std::ifstream fileIN("smth.txt");
std::ofstream fileTMP("smth.txt.tmp");
std::string line = "";
while(getline(fileIN, line))
fileTMP << line << std::endl;
fileIN.close();
fileTMP.close();
std::ifstream file_t_in("smth.txt.tmp"); // file tmp in
std::ofstream fileOUT("smth.txt");
fileOUT << data;
while(getline(file_t_in, line)
fileOUT << line << std::endl;
fileOUT.close();
file_t_in.close();
std::filesystem::remove("smth.txt.tmp");
}
我应该使用 string 还是 ostringstream 或 stringstream?
使用一个比另一个有什么优势?
【问题讨论】:
-
如果你想更快地访问文件,不要读/写“行”,只需在缓冲区的帮助下读/写原始数据。见cplusplus.com/reference/istream/istream/read
标签: c++ string stringstream ostringstream