清除给定大小的C ++文件

时间:2013-07-02 21:33:55

标签: c++ file-io

我有一个经常运行的程序,我希望将日志文件的大小限制在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语句被命中,因为程序输出“清除文件”,但文件没有被清除,最重要的是,“文件已达到限制......”在文件中找不到。但是“启动计划”就在那里。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

unlink不是fstream函数,它是删除文件本身的标准C库函数。

尽管使用ios::outios::trunc打开文件应该可以正常工作。我怀疑您只需要在尝试使用ios::trunc重新打开文件之前关闭该文件。

相关问题