1 krisbash 1.1 #include "file.h"
2 #include <config.h>
3
4 #if defined(PAL_HAVE_POSIX)
5 # include <unistd.h>
6 #endif
7
8 FILE* File_Open(
9 _In_z_ const char* path,
10 _In_z_ const char* mode)
11 {
12 #if defined(_MSC_VER)
13 FILE* fp;
14 return fopen_s(&fp, path, mode) == 0 ? fp : NULL;
15 #else
16 return fopen(path, mode);
17 #endif
18 }
19
20 void File_Close(FILE* fp)
21 {
22 krisbash 1.1 fclose(fp);
23 }
24
25 int File_Remove(
26 _In_z_ const char* path)
27 {
28 #if defined(_MSC_VER)
29 return _unlink(path) == 0 ? 0 : -1;
30 #else
31 return unlink(path) == 0 ? 0 : -1;
32 #endif
33 }
34
35 int File_Touch(
36 _In_z_ const char* path)
37 {
38 FILE* fp = File_Open(path, "w");
39
40 if (!fp)
41 return -1;
42
43 krisbash 1.1 File_Close(fp);
44 return 0;
45 }
46
47 int File_Copy(_In_z_ const char* src, _In_z_ const char* dest)
48 {
49 FILE* is = NULL;
50 FILE* os = NULL;
51 char buf[4096];
52
53 /* Open input file */
54 is = File_Open(src, "rb");
55 if (!is)
56 return -1;
57
58 #if defined(CONFIG_POSIX)
59
60 /* Unlink output file if it exists */
61 if (access(dest, F_OK) == 0)
62 {
63 unlink(dest);
64 krisbash 1.1 }
65
66 #endif
67
68 /* Open output file */
69 os = File_Open(dest, "wb");
70 if (!os)
71 {
72 File_Close(is);
73 return -1;
74 }
75
76 /* Copy file */
77 for (;;)
78 {
79 #if defined(_MSC_VER)
80 long n = (long)fread(buf, 1, sizeof(buf), is);
81 long m;
82 #else
83 ssize_t n = fread(buf, 1, sizeof(buf), is);
84 ssize_t m;
85 krisbash 1.1 #endif
86
87 if (n <= 0)
88 break;
89
90 #if defined(CONFIG_OS_WINDOWS)
91 m = (long)fwrite(buf, 1, n, os);
92 #else
93 m = fwrite(buf, 1, n, os);
94 #endif
95
96 if (m != n)
97 {
98 File_Close(is);
99 File_Close(os);
100 return -1;
101 }
102 }
103
104 File_Close(is);
105 File_Close(os);
106 krisbash 1.1 return 0;
107 }
108
|