1 /* vi: set sw=4 ts=4: */
2 /* fold -- wrap each input line to fit in specified width.
4 Written by David MacKenzie, djm@gnu.ai.mit.edu.
5 Copyright (C) 91, 1995-2002 Free Software Foundation, Inc.
7 Modified for busybox based on coreutils v 5.0
8 Copyright (C) 2003 Glenn McGrath
10 Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
15 static unsigned long flags;
16 #define FLAG_COUNT_BYTES 1
17 #define FLAG_BREAK_SPACES 2
20 /* Assuming the current column is COLUMN, return the column that
21 printing C will move the cursor to.
22 The first column is 0. */
24 static int adjust_column(int column, char c)
26 if (!(flags & FLAG_COUNT_BYTES)) {
33 column = column + 8 - column % 8;
34 else /* if (isprint (c)) */
41 int fold_main(int argc, char **argv);
42 int fold_main(int argc, char **argv)
44 char *line_out = NULL;
45 int allocated_out = 0;
51 if (ENABLE_INCLUDE_SUSv2) {
52 /* Turn any numeric options into -w options. */
53 for (i = 1; i < argc; i++) {
54 char const *a = argv[i];
57 if (*a == '-' && !a[1])
60 argv[i] = xasprintf("-w%s", a);
66 flags = getopt32(argv, "bsw:", &w_opt);
67 if (flags & FLAG_WIDTH)
68 width = xatoul_range(w_opt, 1, 10000);
76 FILE *istream = fopen_or_warn_stdin(*argv);
78 int column = 0; /* Screen column where next char will go. */
79 int offset_out = 0; /* Index in `line_out' for next char. */
81 if (istream == NULL) {
86 while ((c = getc(istream)) != EOF) {
87 if (offset_out + 1 >= allocated_out) {
88 allocated_out += 1024;
89 line_out = xrealloc(line_out, allocated_out);
93 line_out[offset_out++] = c;
94 fwrite(line_out, sizeof(char), (size_t) offset_out, stdout);
95 column = offset_out = 0;
99 column = adjust_column(column, c);
101 if (column > width) {
102 /* This character would make the line too long.
103 Print the line plus a newline, and make this character
104 start the next line. */
105 if (flags & FLAG_BREAK_SPACES) {
106 /* Look for the last blank. */
109 for (logical_end = offset_out - 1; logical_end >= 0; logical_end--) {
110 if (isblank(line_out[logical_end])) {
114 if (logical_end >= 0) {
115 /* Found a blank. Don't output the part after it. */
117 fwrite(line_out, sizeof(char), (size_t) logical_end, stdout);
119 /* Move the remainder to the beginning of the next line.
120 The areas being copied here might overlap. */
121 memmove(line_out, line_out + logical_end, offset_out - logical_end);
122 offset_out -= logical_end;
123 for (column = i = 0; i < offset_out; i++) {
124 column = adjust_column(column, line_out[i]);
129 if (offset_out == 0) {
130 line_out[offset_out++] = c;
134 line_out[offset_out++] = '\n';
135 fwrite(line_out, sizeof(char), (size_t) offset_out, stdout);
136 column = offset_out = 0;
140 line_out[offset_out++] = c;
144 fwrite(line_out, sizeof(char), (size_t) offset_out, stdout);
147 if (ferror(istream) || fclose_if_not_stdin(istream)) {
148 bb_perror_msg("%s", *argv); /* Avoid multibyte problems. */
149 errs |= EXIT_FAILURE;
153 fflush_stdout_and_exit(errs);