umount: getopt return value is int, not char
[minix.git] / commands / split / split.c
blob1fd14aecbf285660db0730b73da0e0933f470dd9
1 /* split - split a file Author: Michiel Huisjes */
3 #include <sys/types.h>
4 #include <fcntl.h>
5 #include <stdlib.h>
6 #include <string.h>
7 #include <unistd.h>
8 #include <minix/minlib.h>
10 #define CHUNK_SIZE 1024
12 int cut_line = 1000;
13 int infile;
14 char out_file[100];
15 char *suffix;
17 int main(int argc, char **argv);
18 void split(void);
19 int newfile(void);
20 void usage(void);
21 void quit(void);
23 int main(argc, argv)
24 int argc;
25 char **argv;
27 unsigned short i;
29 out_file[0] = 'x';
30 infile = -1;
32 if (argc > 4) usage();
33 for (i = 1; i < argc; i++) {
34 if (argv[i][0] == '-') {
35 if (argv[i][1] >= '0' && argv[i][1] <= '9'
36 && cut_line == 1000)
37 cut_line = atoi(argv[i]);
38 else if (argv[i][1] == '\0' && infile == -1)
39 infile = 0;
40 else
41 usage();
42 } else if (infile == -1) {
43 if ((infile = open(argv[i], O_RDONLY)) < 0) {
44 std_err("Cannot open input file.\n");
45 exit(1);
47 } else
48 strcpy(out_file, argv[i]);
50 if (infile == -1) infile = 0;
51 strcat(out_file, "aa");
52 for (suffix = out_file; *suffix; suffix++);
53 suffix--;
55 /* Appendix now points to last `a' of "aa". We have to decrement it by one */
56 *suffix = 'a' - 1;
57 split();
58 return(0);
61 void split()
63 char buf[CHUNK_SIZE];
64 register char *index, *base;
65 register int n;
66 int fd;
67 long lines = 0L;
69 fd = -1;
70 while ((n = read(infile, buf, CHUNK_SIZE)) > 0) {
71 base = index = buf;
72 while (--n >= 0) {
73 if (*index++ == '\n')
74 if (++lines % cut_line == 0) {
75 if (fd == -1) fd = newfile();
76 if (write(fd, base, (int) (index - base)) != (int) (index - base))
77 quit();
78 base = index;
79 close(fd);
80 fd = -1;
83 if (index == base) continue;
84 if (fd == -1) fd = newfile();
85 if (write(fd, base, (int) (index - base)) != (int) (index - base))
86 quit();
90 int newfile()
92 int fd;
94 if (++*suffix > 'z') { /* Increment letter */
95 *suffix = 'a'; /* Reset last letter */
96 ++*(suffix - 1); /* Previous letter must be incremented */
97 /* E.g. was `filename.az' */
98 /* Now `filename.ba' */
100 if ((fd = creat(out_file, 0644)) < 0) {
101 std_err("Cannot create new file.\n");
102 exit(2);
104 return fd;
107 void usage()
109 std_err("Usage: split [-n] [file [name]].\n");
110 exit(1);
113 void quit()
115 std_err("split: write error\n");
116 exit(1);