问题
I am trying to find a cross-platform method to delete X bytes from the end of a file.
Currently I have found:
Platform specific solutions (such as truncate for posix) : This is what I don't want, because I want the C++ program to run on multiple platforms.
Read in the whole file, and write out the file again minus the bytes I want to delete: I would like to avoid this as much as I can since I want the program to be as efficient and fast as possible
Any ideas?
If there is a "go to end of file stream" method/function, could I then rewind X bytes and cut the remainder of the file off or something similar?
回答1:
How do you think cross platform functions work? Just make your own function like this:
int truncate(int fd, long size)
{
#ifdef _WIN32 || _WIN64 
    return _chsize(fd, size);
#else
  #ifdef POSIX
    return ftruncate(fd, size);
  #else
    // code for other OSes
  #endif
#endif
}
    回答2:
There is no such thing in the Standard library. They support streams- but streams don't have ends, files happen to have ends- at the current time.
All you can do is write a cross-platform wrapper on the function.
回答3:
The Boost.Filesystem library (version 1.44 and above) provides a resize_file function.
来源:https://stackoverflow.com/questions/9727287/how-to-truncate-a-file-from-the-end-cross-platform