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 tarball for details.
8 /* BB_AUDIT: SUSv3 compliant
10 * http://www.opengroup.org/onlinepubs/009695399/utilities/split.html
14 static const struct suffix_mult split_suffices[] = {
15 #if ENABLE_FEATURE_SPLIT_FANCY
20 #if ENABLE_FEATURE_SPLIT_FANCY
21 { "g", 1024*1024*1024 },
26 /* Increment the suffix part of the filename.
27 * Returns NULL if we are out of filenames.
29 static char *next_file(char *old, unsigned suffix_len)
31 size_t end = strlen(old);
51 #define read_buffer bb_common_bufsiz1
52 enum { READ_BUFFER_SIZE = COMMON_BUFSIZE - 1 };
54 #define SPLIT_OPT_l (1<<0)
55 #define SPLIT_OPT_b (1<<1)
56 #define SPLIT_OPT_a (1<<2)
58 int split_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
59 int split_main(int argc UNUSED_PARAM, char **argv)
61 unsigned suffix_len = 2;
68 ssize_t bytes_read, to_write;
71 opt_complementary = "?2:a+"; /* max 2 args; -a N */
72 opt = getopt32(argv, "l:b:a:", &count_p, &count_p, &suffix_len);
74 if (opt & SPLIT_OPT_l)
75 cnt = XATOOFF(count_p);
76 if (opt & SPLIT_OPT_b) // FIXME: also needs XATOOFF
77 cnt = xatoull_sfx(count_p, split_suffices);
85 fd = open_or_warn_stdin(argv[0]);
88 xmove_fd(fd, STDIN_FILENO);
90 argv[0] = (char *) bb_msg_standard_input;
93 if (NAME_MAX < strlen(sfx) + suffix_len)
94 bb_error_msg_and_die("suffix too long");
97 char *char_p = xzalloc(suffix_len + 1);
98 memset(char_p, 'a', suffix_len);
99 pfx = xasprintf("%s%s", sfx, char_p);
100 if (ENABLE_FEATURE_CLEAN_UP)
105 bytes_read = safe_read(STDIN_FILENO, read_buffer, READ_BUFFER_SIZE);
109 bb_simple_perror_msg_and_die(argv[0]);
114 bb_error_msg_and_die("suffixes exhausted");
115 xmove_fd(xopen(pfx, O_WRONLY | O_CREAT | O_TRUNC), 1);
116 pfx = next_file(pfx, suffix_len);
120 if (opt & SPLIT_OPT_b) {
122 to_write = (bytes_read < remaining) ? bytes_read : remaining;
123 remaining -= to_write;
126 /* can be sped up by using _memrchr_
127 * and writing many lines at once... */
128 char *end = memchr(src, '\n', bytes_read);
131 to_write = end - src + 1;
133 to_write = bytes_read;
137 xwrite(STDOUT_FILENO, src, to_write);
138 bytes_read -= to_write;
140 } while (bytes_read);