我有一个经常运行的程序,我希望将日志文件的大小限制在 1MB 左右。我已经想出了如何使用tellp和seekp获取文件大小,但是我尝试删除文件的所有操作都不起作用。这是我最新的代码的样子:
std::ofstream myfile("file.txt");
long begin = myfile.tellp();
myfile.seekp(0,std::ios::end);
long end = myfile.tellp();
std::cout << "File size is " << (end - begin) << "\n";
if((end - begin) > 1048576) //1048576 bytes in a megabyte
{
//position the cursor to the beginning of the file
//I don't know if this is necessary but it seemed worth trying
myfile.seekp(0,std::ios::beg);
//opening with trunc erases previous contents (supposedly)
std::cout << "Clearing file\n";
myfile.open("file.txt", std::ios::out | std::ios::trunc);
myfile << "File has reached limit, clearing...\n";
myfile.close();
}
myfile.open("file.txt", std::ios::out | std::ios::app);
myfile << "Starting program\n";
myfile.close();
if 语句被命中,因为程序输出“正在清除文件”,但文件没有被清除,最重要的是,“文件已达到限制...”在文件中无处可寻。但是“启动程序”在那里。有任何想法吗?