From: Junio C Hamano Date: Mon, 14 Sep 2009 19:48:41 GMT Subject: Re: [PATCH 14/17] Add ftruncate implementation for MSVC Message-ID: <7vws41b946.fsf@alter.siamese.dyndns.org> In-Reply-To: Marius Storm-Olsen writes: > The MSVC Posix implementation doesn't contain ftruncate, so add our own > which can handle large files (64bit offsets). > > Signed-off-by: Marius Storm-Olsen > --- > compat/msvc.c | 8 ++++++++ > compat/msvc.h | 2 ++ > 2 files changed, 10 insertions(+), 0 deletions(-) > > diff --git a/compat/msvc.c b/compat/msvc.c > index ac04a4c..b96b045 100644 > --- a/compat/msvc.c > +++ b/compat/msvc.c > @@ -32,4 +32,12 @@ int closedir(DIR *dir) > return 0; > } > > +int ftruncate(int fd, __int64 length) > +{ > + HANDLE fh = (HANDLE)_get_osfhandle(fd); > + if (!fh || _lseeki64(fd, length, SEEK_SET)) > + return -1; > + return SetEndOfFile(fh) ? 0 : -1; > +} > + Wouldn't it break this toy program? ftruncate() should preserve the file offset and use of the seek in the above feels iffy. #include #include #include #include int main(int ac, char **av) { int fd = open("testfile", O_CREAT|O_WRONLY, 0666); if (fd < 0) exit(1); write(fd, "abcdefghijklmnopqrstuvwxyz\n", 27); lseek(fd, 7, SEEK_SET); write(fd, "H", 1); ftruncate(fd, 24); write(fd, "IJ", 2); close(fd); exit(0); } The only two in-tree users of ftruncate() do not care about this, though. They both seek to the beginning and then truncate to zero length.