the file truncate API is limited and inconvenient

Krzysztof Żelechowski giecrilj@stegny.2a.pl
Sat May 8 11:11:00 GMT 2010


Dnia piątek, 7 maja 2010 o 11:16:36 Américo Wang napisał(a):
> On Thu, May 06, 2010 at 08:43:39PM +0200, Krzysztof Żelechowski wrote:
> >2. It is obvious for me that there should be a stdio API with the meaning
> > "let here be the end of this FILE".  I can do this under POSIX by using
> > ftruncate but it requires writing my own subroutine (ftuncate (fileno (),
> > ftell())), and of course there is no C++ way to do this.  How is it
> > possible that nobody ever needed this to be a standard API?
> 
> Well, afaik, file truncation is not supported on all platforms, at least in
>  the past. This is why there is no standard C file truncation function.
> 
> However, you can still do file truncation in a standard way, something
>  like:
> 
> int standard_ftruncate(const char *path, size_t len)
> {
>     fp = fopen(path, "r");
>     buf = malloc(len);
>     fread(buf, 1, len, fp);
>     fp = freopen(path, "w+", fp);
>     fwrite(buf, 1, len, fp);
>     free(buf);
>     fclose(fp);
> }
> 
> Definitely I omitted some return-value checking.
> 

That would not work if there was not enough memory to hold the entire contents 
of the file.  This was very likely to happen on platforms before ftruncate was 
invented.  So the question is how the users of those systems could possibly 
live without such a function.

I mean, if your file is a pile of cards or a punched tape, it is easy to 
dispose of the rest --- but then, those media were read-only by design and 
they could not be refurbished so it did not make much sense either.  Perhaps 
it was the magnetic tape drives that could not truncate a file, but then why 
impose the limitations of tape drives to magnetic discs, at the cost of 
wasting much space that was very expensive?  And this ancient limitation is 
dragged along till today, and even made it into C++.  Unimaginable.

Puzzled,
Chris



More information about the Libc-help mailing list