]> pd.if.org Git - pdclib/blob - platform/win32/functions/_PDCLIB/_PDCLIB_open.c
Initial pass at a port to win32
[pdclib] / platform / win32 / functions / _PDCLIB / _PDCLIB_open.c
1 /* $Id$ */
2
3 /* _PDCLIB_open( char const * const, int )
4
5    This file is part of the Public Domain C Library (PDCLib).
6    Permission is granted to use, modify, and / or redistribute at will.
7 */
8
9 /* This is a stub implementation of open.
10 */
11
12 #include <stdio.h>
13 #include <errno.h>
14
15 #ifndef REGTEST
16 #include <_PDCLIB_glue.h>
17 #include <windows.h>
18
19 void _PDCLIB_w32errno(void);
20 HANDLE _PDCLIB_open( char const * const filename, unsigned int mode )
21 {
22     DWORD desiredAccess;
23     DWORD creationDisposition;
24
25     switch(mode & ( _PDCLIB_FREAD | _PDCLIB_FWRITE | _PDCLIB_FAPPEND 
26                     | _PDCLIB_FRW ))
27     {
28     case _PDCLIB_FREAD: /* "r" */
29         desiredAccess = GENERIC_READ;
30         creationDisposition = OPEN_EXISTING;
31         break;
32     case _PDCLIB_FWRITE: /* "w" */
33         desiredAccess = GENERIC_WRITE;
34         creationDisposition = CREATE_ALWAYS;
35         break;
36     case _PDCLIB_FAPPEND: /* "a" */
37         desiredAccess = GENERIC_WRITE;
38         creationDisposition = OPEN_ALWAYS;
39         break;
40     case _PDCLIB_FREAD | _PDCLIB_FRW: /* "r+" */
41         desiredAccess = GENERIC_READ | GENERIC_WRITE;
42         creationDisposition = OPEN_EXISTING;
43         break;
44     case _PDCLIB_FWRITE | _PDCLIB_FRW: /* "w+" */
45         desiredAccess = GENERIC_WRITE | GENERIC_READ;
46         creationDisposition = CREATE_ALWAYS;
47         break;
48     case _PDCLIB_FAPPEND | _PDCLIB_FRW: /* "a+" */
49         desiredAccess = GENERIC_WRITE | GENERIC_READ;
50         creationDisposition = OPEN_ALWAYS;
51         break;
52     default: /* Invalid mode */
53         errno = EINVAL;
54         return NULL;
55     }
56
57     HANDLE fd = CreateFileA(filename, desiredAccess, 
58         FILE_SHARE_READ | FILE_SHARE_DELETE,
59         NULL, creationDisposition, FILE_ATTRIBUTE_NORMAL, NULL);
60
61     if(fd == INVALID_HANDLE_VALUE) {
62         _PDCLIB_w32errno();
63         return NULL;
64     }
65
66     if(mode & _PDCLIB_FAPPEND) {
67         LARGE_INTEGER offs;
68         offs.QuadPart = 0;
69         BOOL ok = SetFilePointerEx(fd, offs, NULL, FILE_END);
70         if(!ok) {
71             _PDCLIB_w32errno();
72             CloseHandle(fd);
73             return NULL;
74         }
75     }
76
77     return fd;
78 }
79
80 #endif
81
82 #ifdef TEST
83 #include <_PDCLIB_test.h>
84
85 #include <stdlib.h>
86 #include <string.h>
87
88 int main( void )
89 {
90     return TEST_RESULTS;
91 }
92
93 #endif
94