This is the mail archive of the
libc-help@sourceware.org
mailing list for the glibc project.
Re: the file truncate API is limited and inconvenient
- From: AmÃrico Wang <xiyou dot wangcong at gmail dot com>
- To: Krzysztof Åelechowski <giecrilj at stegny dot 2a dot pl>
- Cc: libc-help at sourceware dot org
- Date: Fri, 7 May 2010 17:16:36 +0800
- Subject: Re: the file truncate API is limited and inconvenient
- References: <201005062043.39657.giecrilj@stegny.2a.pl>
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.