“我可能会创建一个新文件,在旧文件中查找,从旧文件到新文件进行缓冲读/写,将新文件重命名为旧文件。”
我认为你最好还是简单点:
#include <fstream>
std::ifstream ifs("logfile"); //One call to start it all. . .
ifs.seekg(-512000, std::ios_base::end); // One call to find it. . .
char tmpBuffer[512000];
ifs.read(tmpBuffer, 512000); //One call to read it all. . .
ifs.close();
std::ofstream ofs("logfile", ios::trunc);
ofs.write(tmpBuffer, 512000); //And to the FS bind it.
这可以避免文件重命名,只需将最后的 512K 复制到缓冲区,以截断模式打开日志文件(清除日志文件的内容),然后将相同的 512K 吐回到文件的开头。
请注意,上面的代码还没有经过测试,但我认为这个想法应该是合理的。
您可以将 512K 加载到内存中的缓冲区中,关闭输入流,然后打开输出流;这样,您将不需要两个文件,因为您输入、关闭、打开、输出 512 个字节,然后继续。您可以通过这种方式避免重命名/文件重定位魔法。
如果您在某种程度上不反对将 C 与 C++ 混合使用,您也可以:
(注意:伪代码;我不记得我脑海中的 mmap 调用)
int myfd = open("mylog", O_RDONLY); // Grab a file descriptor
(char *) myptr = mmap(mylog, myfd, filesize - 512000) // mmap the last 512K
std::string mystr(myptr, 512000) // pull 512K from our mmap'd buffer and load it directly into the std::string
munmap(mylog, 512000); //Unmap the file
close(myfd); // Close the file descriptor
取决于很多事情,mmap 可能比寻找更快。如果你好奇的话,谷歌搜索“fseek vs mmap”会产生一些有趣的信息。
HTH