1 /* vi: set sw=4 ts=4: */
3 * split - split a file into pieces
4 * Copyright (c) 2007 Bernhard Reutner-Fischer
6 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
8 /* BB_AUDIT: SUSv3 compliant
10 * http://www.opengroup.org/onlinepubs/009695399/utilities/split.html
13 //usage:#define split_trivial_usage
14 //usage: "[OPTIONS] [INPUT [PREFIX]]"
15 //usage:#define split_full_usage "\n\n"
17 //usage: "\n -b N[k|m] Split by N (kilo|mega)bytes"
18 //usage: "\n -l N Split by N lines"
19 //usage: "\n -a N Use N letters as suffix"
21 //usage:#define split_example_usage
22 //usage: "$ split TODO foo\n"
23 //usage: "$ cat TODO | split -a 2 -l 2 TODO_\n"
27 static const struct suffix_mult split_suffices[] = {
28 #if ENABLE_FEATURE_SPLIT_FANCY
33 #if ENABLE_FEATURE_SPLIT_FANCY
34 { "g", 1024*1024*1024 },
39 /* Increment the suffix part of the filename.
40 * Returns NULL if we are out of filenames.
42 static char *next_file(char *old, unsigned suffix_len)
44 size_t end = strlen(old);
64 #define read_buffer bb_common_bufsiz1
65 enum { READ_BUFFER_SIZE = COMMON_BUFSIZE - 1 };
67 #define SPLIT_OPT_l (1<<0)
68 #define SPLIT_OPT_b (1<<1)
69 #define SPLIT_OPT_a (1<<2)
71 int split_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
72 int split_main(int argc UNUSED_PARAM, char **argv)
74 unsigned suffix_len = 2;
81 ssize_t bytes_read, to_write;
84 opt_complementary = "?2:a+"; /* max 2 args; -a N */
85 opt = getopt32(argv, "l:b:a:", &count_p, &count_p, &suffix_len);
87 if (opt & SPLIT_OPT_l)
88 cnt = XATOOFF(count_p);
89 if (opt & SPLIT_OPT_b) // FIXME: also needs XATOOFF
90 cnt = xatoull_sfx(count_p, split_suffices);
98 fd = xopen_stdin(argv[0]);
99 xmove_fd(fd, STDIN_FILENO);
101 argv[0] = (char *) bb_msg_standard_input;
104 if (NAME_MAX < strlen(sfx) + suffix_len)
105 bb_error_msg_and_die("suffix too long");
108 char *char_p = xzalloc(suffix_len + 1);
109 memset(char_p, 'a', suffix_len);
110 pfx = xasprintf("%s%s", sfx, char_p);
111 if (ENABLE_FEATURE_CLEAN_UP)
116 bytes_read = safe_read(STDIN_FILENO, read_buffer, READ_BUFFER_SIZE);
120 bb_simple_perror_msg_and_die(argv[0]);
125 bb_error_msg_and_die("suffixes exhausted");
126 xmove_fd(xopen(pfx, O_WRONLY | O_CREAT | O_TRUNC), 1);
127 pfx = next_file(pfx, suffix_len);
131 if (opt & SPLIT_OPT_b) {
133 to_write = (bytes_read < remaining) ? bytes_read : remaining;
134 remaining -= to_write;
137 /* can be sped up by using _memrchr_
138 * and writing many lines at once... */
139 char *end = memchr(src, '\n', bytes_read);
142 to_write = end - src + 1;
144 to_write = bytes_read;
148 xwrite(STDOUT_FILENO, src, to_write);
149 bytes_read -= to_write;
151 } while (bytes_read);