moved copy fcts to separate file
[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
23 #include "io.h"
24
25 #define FCOPY_BUF_SZ 4096
26
27 static int file_copy(FILE *src, FILE *dst)
28 {
29         int ret = 0;
30         char *buf = malloc(FCOPY_BUF_SZ);
31         int n;
32
33         if (!buf)
34                 return FILE_COPY_ERROR_ALLOC_BUFFER;
35
36         while (!ret) {
37                 n = fread(buf, 1, FCOPY_BUF_SZ, src);
38                 if (n) {
39                         if (fwrite(buf, 1, n, dst) != n)
40                                 ret = FILE_COPY_ERROR_WRITE;
41                 } else {
42                         if (!feof(src))
43                                 ret = FILE_COPY_ERROR_READ;
44                         else
45                                 break;
46                 }
47         }
48
49         free(buf);
50
51         return ret;
52 }
53
54 int fcopy(const char *src, const char *dst)
55 {
56         FILE *fsrc, *fdst;
57         int ret = 0;
58
59         fsrc = fopen(src, "r");
60
61         if (fsrc) {
62                 fdst = fopen(dst, "w+");
63
64                 if (fdst) {
65                         ret = file_copy(fsrc, fdst);
66                         fclose(fdst);
67                 } else {
68                         ret = FILE_COPY_ERROR_OPEN_DST;
69                 }
70
71                 fclose(fsrc);
72         } else {
73                 ret = FILE_COPY_ERROR_OPEN_SRC;
74         }
75
76         return ret;
77 }