Statistiques
| Branche: | Révision :

root / split.c @ master

Historique | Voir | Annoter | Télécharger (1,88 ko)

1
/*
2
 * Copyright (c) 2005 by Romuald DELAVERGNE
3
 * It can be redistributed under the terms of the GNU General Public License.
4
*/
5
#include <stdlib.h>
6
#include <stdio.h>
7
#include <string.h>
8
#include <sys/stat.h>
9
#include <io.h>
10
11
void
12
exitOnError(char *msg) {
13
        perror(msg);
14
        exit(1);
15
}
16
17
int
18
main(int argc, char *argv[]) {
19
        void *buf;
20
        struct stat statFileIn;
21
        FILE *fileIn, *fileOut;
22
        char
23
                fileName[255],
24
                *prog = argv[0],
25
                *prefix = argv[3];
26
        unsigned long
27
                nbFiles, lastSize, maxSize, size, nb, nbWrited, nbRest;
28
        int i;
29
30
        buf = malloc(BUFSIZ);
31
32
        if (argc < 4) {
33
                printf("%s: too few parameters !\n", prog);
34
                printf("split a file into pieces\n");
35
                printf("usage: %s FILE SIZE PREFIX\n", prog);
36
                printf("  FILE  : big file to split\n");
37
                printf("  SIZE  : size in bytes\n");
38
                printf("  PREFIX: result files without suffix\n");
39
                exit(0);
40
        }
41
42
        if ((fileIn = fopen(argv[1], "rb")) == NULL) exitOnError(argv[1]);
43
        if (fstat(fileIn->fd, &statFileIn) == -1) exitOnError(argv[1]);
44
        if (sscanf(argv[2], "%lu", &maxSize) == 0) {
45
                fprintf(stderr, "%s: invalid size !\n", argv[2]);
46
                exit(1);
47
        }
48
        nbFiles = statFileIn.st_size/maxSize;
49
        lastSize = statFileIn.st_size%maxSize;
50
        if (lastSize > 0) nbFiles++; else lastSize = maxSize;
51
        i = 0;
52
        while (i < nbFiles) {
53
                i++;
54
                size = (i == nbFiles) ? lastSize: maxSize;
55
                sprintf(fileName, "%s.%03d", prefix, i);
56
                if (access(fileName, 0) == 0) {
57
                        fprintf(stderr, "%s: file already exists !\n", fileName);
58
                        exit(1);
59
                }
60
                if ((fileOut = fopen(fileName, "wb")) == NULL) exitOnError(fileName);
61
                nbWrited = 0;
62
                while (nbWrited < size) {
63
                        nbRest = size - nbWrited;
64
                        nb = (nbRest < BUFSIZ) ? nbRest: BUFSIZ;
65
                        if (fread(buf, nb, 1, fileIn) != 1) exitOnError(prog);
66
                        if (fwrite(buf, nb, 1, fileOut) != 1) exitOnError(prog);
67
                        nbWrited += nb;
68
                }
69
                fclose(fileOut);
70
        }
71
        fclose(fileIn);
72
73
        return 0;
74
}