OSDN Git Service

debugging code was removed.
[lha/olha.git] / filelib.c
1 #include <stdio.h>
2 #include <sys/types.h>
3 #include <sys/stat.h>
4 #include <unistd.h>
5 #include <errno.h>
6 #include <string.h>
7
8 int
9 file_exists(char *file)
10 {
11     struct stat st;
12     int ret;
13
14     ret = stat(file, &st);
15     if (ret == -1) {
16         switch (errno) {
17         case ENOENT:
18             return 0;
19         case ENAMETOOLONG:
20             warn("enametoolong: %d", strlen(file));
21             return 0;
22         default:
23             error("failed to stat() for '%s' (%s)", file, strerror(errno));
24         }
25     }
26
27     /* file exists */
28     return 1;
29 }
30
31 int
32 file_mtime(char *file, time_t *t)
33 {
34     struct stat st;
35     int ret;
36
37     ret = stat(file, &st);
38     if (ret == -1) {
39         if (errno == ENOENT)
40             return -1;
41         else
42             error("failed to stat() for '%s' (%s)", file, strerror(errno));
43     }
44
45     *t = st.st_mtime;
46     return 0;
47 }
48
49 int
50 copy_stream(FILE *rfp, FILE *wfp)
51 {
52     int readsz;
53     char buf[BUFSIZ];
54
55     while ((readsz = fread(buf, 1, sizeof(buf), rfp)) != 0) {
56         if (fwrite(buf, readsz, 1, wfp) == 0) {
57             return -1;
58         }
59     }
60
61     if (ferror(rfp)) {
62         return -1;
63     }
64
65     return 0;
66 }
67
68 int
69 move_file_to_stream(char *file, FILE *wfp)
70 {
71     FILE *rfp = NULL;
72
73     if ((rfp = fopen(file, "r")) == NULL)
74         goto err;
75
76     copy_stream(rfp, wfp);
77
78     if (rfp) fclose(rfp);
79
80     unlink(file);
81
82     return 0;
83 err:
84     if (rfp) fclose(rfp);
85
86     return -1;
87 }
88
89 int
90 xrename(char *from, char *to)
91 {
92     FILE *rfp = NULL, *wfp = NULL;
93
94     if ((rfp = fopen(from, "r")) == NULL)
95         goto err;
96
97     if ((wfp = fopen(to, "w")) == NULL)
98         goto err;
99
100     copy_stream(rfp, wfp);
101
102     if (rfp) fclose(rfp);
103     if (wfp) fclose(wfp);
104
105     unlink(from);
106
107     return 0;
108 err:
109     if (rfp) fclose(rfp);
110     if (wfp) fclose(wfp);
111
112     return -1;
113 }