4

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?

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
midnightBlue
  • 1,735
  • 2
  • 13
  • 13

3 Answers3

4

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
}
David Sykes
  • 48,469
  • 17
  • 71
  • 80
GreenScape
  • 7,191
  • 2
  • 34
  • 64
1

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.

Puppy
  • 144,682
  • 38
  • 256
  • 465
  • Ok... a slightly different but related question; For a given OS, say windows. How exactly does the OS know when its reached the end of a file? Is there an EOF byte or something similar? If so, what is the implementation of this in other platforms? (e.g. linux) – midnightBlue Mar 16 '12 at 01:45
  • I asked this because I was wondering if it was possible to simply put that byte when I want to truncate it off. – midnightBlue Mar 16 '12 at 01:45
0

The Boost.Filesystem library (version 1.44 and above) provides a resize_file function.

Josh Kelley
  • 56,064
  • 19
  • 146
  • 246