Thread (1 message) 1 message, 1 author, 2016-06-15

Re: [PATCH 14/17] Add ftruncate implementation for MSVC

From: Junio C Hamano <hidden>
Date: 2016-06-15 22:47:24

Marius Storm-Olsen [off-list ref] writes:
quoted hunk
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 <redacted>
---
 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 <stdlib.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>

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.
Keyboard shortcuts
hback out one level
jnext message in thread
kprevious message in thread
ldrill in
Escclose help / fold thread tree
?toggle this help