]> pd.if.org Git - pdclib/blob - platform/win32/functions/_PDCLIB/_PDCLIB_fileops.c
dos2unix
[pdclib] / platform / win32 / functions / _PDCLIB / _PDCLIB_fileops.c
1 /* _PDCLIB_fileops
2
3    This file is part of the Public Domain C Library (PDCLib).
4    Permission is granted to use, modify, and / or redistribute at will.
5 */
6
7 #ifndef REGTEST
8 #include <stdio.h>
9 #include <stdint.h>
10 #include "_PDCLIB_glue.h"
11 #include <errno.h>
12 #include <windows.h>
13
14 #if _PDCLIB_C_MIN(2011)
15 _Static_assert(SEEK_SET == FILE_BEGIN, "SEEK_SET is incorrect");
16 _Static_assert(SEEK_CUR == FILE_CURRENT, "SEEK_CUR is incorrect");
17 _Static_assert(SEEK_END == FILE_END, "SEEK_END is incorrect");
18 #endif
19
20 void _PDCLIB_w32errno(void);
21
22 static bool readf( _PDCLIB_fd_t self, void * buf, size_t length, 
23                    size_t * numBytesRead )
24 {
25     DWORD dwLen = length > INT32_MAX ? INT32_MAX : length;
26     DWORD dwBytesRead;
27     if(ReadFile(self.pointer, buf, dwLen, &dwBytesRead, NULL)) {
28         *numBytesRead = dwBytesRead;
29         return true;
30     } else {
31         _PDCLIB_w32errno();
32         return false;
33     }
34 }
35
36 static bool writef( _PDCLIB_fd_t self, const void * buf, size_t length, 
37                    size_t * numBytesWritten )
38 {
39     DWORD dwLen = length > INT32_MAX ? INT32_MAX : length;
40     DWORD dwBytesWritten;
41
42     if(WriteFile(self.pointer, buf, dwLen, &dwBytesWritten, NULL)) {
43         *numBytesWritten = dwBytesWritten;
44         return true;
45     } else {
46         _PDCLIB_w32errno();
47         return false;
48     }
49 }
50 static bool seekf( _PDCLIB_fd_t self, int_fast64_t offset, int whence,
51     int_fast64_t* newPos )
52 {
53     LARGE_INTEGER liOffset;
54     liOffset.QuadPart = offset;
55     if(!SetFilePointerEx( self.pointer, liOffset, &liOffset, whence )) {
56         _PDCLIB_w32errno();
57         return false;
58     }
59
60     *newPos = liOffset.QuadPart;
61     return true;
62 }
63
64 static void closef( _PDCLIB_fd_t self )
65 {
66     CloseHandle( self.pointer );
67 }
68
69 const _PDCLIB_fileops_t _PDCLIB_fileops = {
70     .read  = readf,
71     .write = writef,
72     .seek  = seekf,
73     .close = closef,
74 };
75
76 #endif
77
78 #ifdef TEST
79 #include "_PDCLIB_test.h"
80
81 int main( void )
82 {
83     // Tested by stdio test cases
84     return TEST_RESULTS;
85 }
86
87 #endif