summaryrefslogtreecommitdiff
path: root/reference/C/CONTRIB/SNIP/split.c
blob: cd3b978a388b7107df8ffec8932fac6db46af026 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/*
**  SPLIT.C - A utility to split large text files into smaller files
**
**  public domain by Bob Stout
**
**  uses PSPLIT.C from SNIPPETS
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#ifdef __TURBOC__
 #define FAR far
#else
 #define FAR _far
#endif

void psplit(char *, char *, char *, char *, char *);

int main(int argc, char *argv[])
{
      long newsize = 32L * 1024L;
      size_t seq = 0;
      char fname[FILENAME_MAX];
      FILE *from;

      if (2 > argc)
      {
            puts("SPLIT big_file [size_in_K]\n");
            puts("creates files of the same name, "
                  "but with numeric extensions");
            puts("a maximum file size may be specified for new files");
            return EXIT_SUCCESS;
      }
      if (2 < argc)
      {
            newsize   = atol(argv[2]);
            newsize <<= 10;
      }
      if (NULL == (from = fopen(argv[1], "r")))
      {
            printf("\aSPLIT: error - can't open %s\n", argv[1]);
            return EXIT_FAILURE;
      }
      psplit(argv[1], NULL, NULL, fname, NULL);
      while (!feof(from))
      {
            char newname[FILENAME_MAX], buf[1024];
            FILE *to;
            long bytes;

            sprintf(newname, "%s.%03d", fname, seq++);
            if (NULL == (to = fopen(newname, "w")))
            {
                  printf("\aSPLIT: error - can't write %s\n", newname);
                  return EXIT_FAILURE;
            }
            for (bytes = 0L; !feof(from) && (bytes < newsize); )
            {
                  if (fgets(buf, 1023, from))
                  {
                        fputs(buf, to);
                        bytes += (long)strlen(buf);
                  }
            }
            fclose(to);
            printf("%s written\n", newname);
      }
      return EXIT_SUCCESS;
}