1 /* vi: set sw=4 ts=4: */
3 * split - split a file into pieces
4 * Copyright (c) 2007 Bernhard Fischer
6 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
8 /* BB_AUDIT: not yet SUSV3 compliant; FIXME: add -bN{k,m}
10 * http://www.opengroup.org/onlinepubs/009695399/utilities/split.html
13 static unsigned suffix_len = 2;
15 /* Increment the suffix part of the filename.
16 * Returns 0 on success and 1 on error (if we are out of files)
18 static bool next_file(char **old)
20 size_t end = strlen(*old);
25 // if (**(old + end - i) < 'z') {
26 curr = *old + end - i;
28 *(*old + end - i) += 1;
31 *(*old +end - i) = 'a';
33 } while (i <= suffix_len);
34 if ((*curr == 'z') && (i == suffix_len))
38 #define SPLIT_OPT_l (1<<0)
39 #define SPLIT_OPT_b (1<<1)
41 int split_main(int argc, char **argv);
42 int split_main(int argc, char **argv)
50 //XXX: FIXME opt_complementary = "+2"; /* at most 2 non-option arguments */
51 getopt32(argc, argv, "l:b:a:", &count_p, &count_p, &sfx_len);
57 suffix_len = xatoul(sfx_len);
60 *--argv = (char*) "-";
62 if (NAME_MAX < strlen(*argv) + suffix_len)
63 bb_error_msg_and_die("Suffix too long");
66 char *char_p = xzalloc(suffix_len);
67 memset(char_p, 'a', suffix_len);
68 pfx = xasprintf("%s%s", (argc > optind + 1) ? *++argv : "x", char_p);
69 if (ENABLE_FEATURE_CLEAN_UP)
72 //XXX:FIXME: unify those two file-handling schemata below (FILE vs fd) !
73 if (option_mask32 & SPLIT_OPT_b) {
77 int inp = xopen(input_file, O_RDONLY);
78 int flags = O_WRONLY | O_CREAT | O_TRUNC;
80 int out = xopen(pfx, flags);
82 lseek(inp, bytes, SEEK_SET);
83 bytes += i = full_read(inp, buf, cnt);
88 flags = O_WRONLY | O_APPEND;
91 FILE *fp = fopen_or_warn_stdin(input_file);
95 int flags = O_WRONLY | O_CREAT | O_TRUNC;
96 int out = xopen(pfx, flags);
99 buf = xmalloc_fgets(fp);
102 xwrite(out, buf, buf ? strlen(buf) : 0);
108 flags = O_WRONLY | O_APPEND;
110 if (ENABLE_FEATURE_CLEAN_UP)
111 fclose_if_not_stdin(fp);
114 if (ENABLE_FEATURE_CLEAN_UP) {