4

I am trying to partially truncate (or shorten) an existing file, using fstream. I have tried writing an EOF character, but this seems to do nothing.

Any help would be appreciated...

Paul Ridgway
  • 1,015
  • 1
  • 13
  • 22

4 Answers4

3

I don't think you can. There are many functions for moving "up and down" the wrapper hierarchy for HANDLE<->int<->FILE *, at least on Windows, but there is no "proper" to extract the FILE * from an iostreams object (if indeed it is even implemented with one).

You may find this question to be of assistance.

Personally I would strongly recommend steering clear of iostreams, they're poorly designed, heavily C++, and nasty to look at. Take a look at Boost's iostreams, or wrap stdio.h if you need to use classes.

The relevant function for stdio is ftruncate().

Community
  • 1
  • 1
Matt Joiner
  • 100,604
  • 94
  • 332
  • 495
1

The Boost.Interprocess library defines a portable truncate function. For some reason it is not documented, but you can find it this header file.

Manuel
  • 11,909
  • 1
  • 24
  • 35
0

It'll depend on the OS. Most OSes support this, but in different ways. On Windows, there's a SetEndOfFile(). On Unix and similar systems, you lseek to where you want the file to end, and do an lwrite of zero bytes there. Other OSes undoubtedly use other methods.

Jerry Coffin
  • 437,173
  • 71
  • 570
  • 1,035
0

I bit the bullet in the end and read the part of the file to be kept to an array then re-wrote it. It's not the best solution - but as the files will always be small I have decided to accept this method.

Paul Ridgway
  • 1,015
  • 1
  • 13
  • 22
  • 1
    Why not just use C file I/O and do it directly, rather than working around the limitations imposed by C++ streams (which seem the wrong tool for your task)? – John Zwinck Feb 15 '10 at 17:17