aeeed8c962c3f9e8c57f29fa57d93b461f18d6f8
[ppastats.git] / src / io.c
1 /*
2  * Copyright (C) 2011 jeanfi@gmail.com
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License as
6  * published by the Free Software Foundation; either version 2 of the
7  * License, or (at your option) any later version.
8
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
17  * 02110-1301 USA
18  */
19
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <string.h>
23
24 #include "io.h"
25
26 #define FCOPY_BUF_SZ 4096
27
28 static int file_copy(FILE *src, FILE *dst)
29 {
30         int ret = 0;
31         char *buf = malloc(FCOPY_BUF_SZ);
32         int n;
33
34         if (!buf)
35                 return FILE_COPY_ERROR_ALLOC_BUFFER;
36
37         while (!ret) {
38                 n = fread(buf, 1, FCOPY_BUF_SZ, src);
39                 if (n) {
40                         if (fwrite(buf, 1, n, dst) != n)
41                                 ret = FILE_COPY_ERROR_WRITE;
42                 } else {
43                         if (!feof(src))
44                                 ret = FILE_COPY_ERROR_READ;
45                         else
46                                 break;
47                 }
48         }
49
50         free(buf);
51
52         return ret;
53 }
54
55 int fcopy(const char *src, const char *dst)
56 {
57         FILE *fsrc, *fdst;
58         int ret = 0;
59
60         fsrc = fopen(src, "r");
61
62         if (fsrc) {
63                 fdst = fopen(dst, "w+");
64
65                 if (fdst) {
66                         ret = file_copy(fsrc, fdst);
67                         fclose(fdst);
68                 } else {
69                         ret = FILE_COPY_ERROR_OPEN_DST;
70                 }
71
72                 fclose(fsrc);
73         } else {
74                 ret = FILE_COPY_ERROR_OPEN_SRC;
75         }
76
77         return ret;
78 }
79
80 char *path_append(const char *odir, const char *name)
81 {
82         char *dir;
83
84         dir = malloc(strlen(odir)+1+strlen(name)+1);
85
86         sprintf(dir, "%s/%s", odir, name);
87
88         return dir;
89 }
90