Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<blockquote> <p>"I would probably create a new file, seek in the old file, do a buffered read/write from old file to new file, rename the new file over the old one."</p> </blockquote> <p>I think you'd be better off simply:</p> <pre><code>#include &lt;fstream&gt; 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. </code></pre> <p>This avoids the file rename stuff by simply copying the last 512K to a buffer, opening your logfile in truncate mode (clears the contents of the logfile), and spitting that same 512K back into the beginning of the file.</p> <p>Note that the above code hasn't been tested, but I think the idea should be sound.</p> <p>You could load the 512K into a buffer in memory, close the input stream, then open the output stream; in this way, you wouldn't need two files since you'd input, close, open, output the 512 bytes, then go. You avoid the rename / file relocation magic this way.</p> <p>If you don't have an aversion to mixing C with C++ to some extent, you could also perhaps:</p> <p>(Note: pseudocode; I don't remember the mmap call off the top of my head)</p> <pre><code>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 </code></pre> <p>Depending on many things, mmap <em>could be</em> faster than seeking. Googling 'fseek vs mmap' yields some interesting reading about it, if you're curious.</p> <p>HTH</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload