df: add --output=file to directly output specified arguments
[coreutils.git] / src / fold.c
blobe2358651a81d5793e8bd8abd2080dbf923ae0d6a
1 /* fold -- wrap each input line to fit in specified width.
2 Copyright (C) 1991-2013 Free Software Foundation, Inc.
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>. */
17 /* Written by David MacKenzie, djm@gnu.ai.mit.edu. */
19 #include <config.h>
21 #include <stdio.h>
22 #include <getopt.h>
23 #include <sys/types.h>
25 #include "system.h"
26 #include "error.h"
27 #include "fadvise.h"
28 #include "quote.h"
29 #include "xstrtol.h"
31 #define TAB_WIDTH 8
33 /* The official name of this program (e.g., no 'g' prefix). */
34 #define PROGRAM_NAME "fold"
36 #define AUTHORS proper_name ("David MacKenzie")
38 /* If nonzero, try to break on whitespace. */
39 static bool break_spaces;
41 /* If nonzero, count bytes, not column positions. */
42 static bool count_bytes;
44 /* If nonzero, at least one of the files we read was standard input. */
45 static bool have_read_stdin;
47 static char const shortopts[] = "bsw:0::1::2::3::4::5::6::7::8::9::";
49 static struct option const longopts[] =
51 {"bytes", no_argument, NULL, 'b'},
52 {"spaces", no_argument, NULL, 's'},
53 {"width", required_argument, NULL, 'w'},
54 {GETOPT_HELP_OPTION_DECL},
55 {GETOPT_VERSION_OPTION_DECL},
56 {NULL, 0, NULL, 0}
59 void
60 usage (int status)
62 if (status != EXIT_SUCCESS)
63 emit_try_help ();
64 else
66 printf (_("\
67 Usage: %s [OPTION]... [FILE]...\n\
68 "),
69 program_name);
70 fputs (_("\
71 Wrap input lines in each FILE (standard input by default), writing to\n\
72 standard output.\n\
73 "), stdout);
75 emit_mandatory_arg_note ();
77 fputs (_("\
78 -b, --bytes count bytes rather than columns\n\
79 -s, --spaces break at spaces\n\
80 -w, --width=WIDTH use WIDTH columns instead of 80\n\
81 "), stdout);
82 fputs (HELP_OPTION_DESCRIPTION, stdout);
83 fputs (VERSION_OPTION_DESCRIPTION, stdout);
84 emit_ancillary_info ();
86 exit (status);
89 /* Assuming the current column is COLUMN, return the column that
90 printing C will move the cursor to.
91 The first column is 0. */
93 static size_t
94 adjust_column (size_t column, char c)
96 if (!count_bytes)
98 if (c == '\b')
100 if (column > 0)
101 column--;
103 else if (c == '\r')
104 column = 0;
105 else if (c == '\t')
106 column += TAB_WIDTH - column % TAB_WIDTH;
107 else /* if (isprint (c)) */
108 column++;
110 else
111 column++;
112 return column;
115 /* Fold file FILENAME, or standard input if FILENAME is "-",
116 to stdout, with maximum line length WIDTH.
117 Return true if successful. */
119 static bool
120 fold_file (char const *filename, size_t width)
122 FILE *istream;
123 int c;
124 size_t column = 0; /* Screen column where next char will go. */
125 size_t offset_out = 0; /* Index in 'line_out' for next char. */
126 static char *line_out = NULL;
127 static size_t allocated_out = 0;
128 int saved_errno;
130 if (STREQ (filename, "-"))
132 istream = stdin;
133 have_read_stdin = true;
135 else
136 istream = fopen (filename, "r");
138 if (istream == NULL)
140 error (0, errno, "%s", filename);
141 return false;
144 fadvise (istream, FADVISE_SEQUENTIAL);
146 while ((c = getc (istream)) != EOF)
148 if (offset_out + 1 >= allocated_out)
149 line_out = X2REALLOC (line_out, &allocated_out);
151 if (c == '\n')
153 line_out[offset_out++] = c;
154 fwrite (line_out, sizeof (char), offset_out, stdout);
155 column = offset_out = 0;
156 continue;
159 rescan:
160 column = adjust_column (column, c);
162 if (column > width)
164 /* This character would make the line too long.
165 Print the line plus a newline, and make this character
166 start the next line. */
167 if (break_spaces)
169 bool found_blank = false;
170 size_t logical_end = offset_out;
172 /* Look for the last blank. */
173 while (logical_end)
175 --logical_end;
176 if (isblank (to_uchar (line_out[logical_end])))
178 found_blank = true;
179 break;
183 if (found_blank)
185 size_t i;
187 /* Found a blank. Don't output the part after it. */
188 logical_end++;
189 fwrite (line_out, sizeof (char), (size_t) logical_end,
190 stdout);
191 putchar ('\n');
192 /* Move the remainder to the beginning of the next line.
193 The areas being copied here might overlap. */
194 memmove (line_out, line_out + logical_end,
195 offset_out - logical_end);
196 offset_out -= logical_end;
197 for (column = i = 0; i < offset_out; i++)
198 column = adjust_column (column, line_out[i]);
199 goto rescan;
203 if (offset_out == 0)
205 line_out[offset_out++] = c;
206 continue;
209 line_out[offset_out++] = '\n';
210 fwrite (line_out, sizeof (char), (size_t) offset_out, stdout);
211 column = offset_out = 0;
212 goto rescan;
215 line_out[offset_out++] = c;
218 saved_errno = errno;
220 if (offset_out)
221 fwrite (line_out, sizeof (char), (size_t) offset_out, stdout);
223 if (ferror (istream))
225 error (0, saved_errno, "%s", filename);
226 if (!STREQ (filename, "-"))
227 fclose (istream);
228 return false;
230 if (!STREQ (filename, "-") && fclose (istream) == EOF)
232 error (0, errno, "%s", filename);
233 return false;
236 return true;
240 main (int argc, char **argv)
242 size_t width = 80;
243 int i;
244 int optc;
245 bool ok;
247 initialize_main (&argc, &argv);
248 set_program_name (argv[0]);
249 setlocale (LC_ALL, "");
250 bindtextdomain (PACKAGE, LOCALEDIR);
251 textdomain (PACKAGE);
253 atexit (close_stdout);
255 break_spaces = count_bytes = have_read_stdin = false;
257 while ((optc = getopt_long (argc, argv, shortopts, longopts, NULL)) != -1)
259 char optargbuf[2];
261 switch (optc)
263 case 'b': /* Count bytes rather than columns. */
264 count_bytes = true;
265 break;
267 case 's': /* Break at word boundaries. */
268 break_spaces = true;
269 break;
271 case '0': case '1': case '2': case '3': case '4':
272 case '5': case '6': case '7': case '8': case '9':
273 if (optarg)
274 optarg--;
275 else
277 optargbuf[0] = optc;
278 optargbuf[1] = '\0';
279 optarg = optargbuf;
281 /* Fall through. */
282 case 'w': /* Line width. */
284 unsigned long int tmp_ulong;
285 if (! (xstrtoul (optarg, NULL, 10, &tmp_ulong, "") == LONGINT_OK
286 && 0 < tmp_ulong && tmp_ulong < SIZE_MAX - TAB_WIDTH))
287 error (EXIT_FAILURE, 0,
288 _("invalid number of columns: %s"), quote (optarg));
289 width = tmp_ulong;
291 break;
293 case_GETOPT_HELP_CHAR;
295 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
297 default:
298 usage (EXIT_FAILURE);
302 if (argc == optind)
303 ok = fold_file ("-", width);
304 else
306 ok = true;
307 for (i = optind; i < argc; i++)
308 ok &= fold_file (argv[i], width);
311 if (have_read_stdin && fclose (stdin) == EOF)
312 error (EXIT_FAILURE, errno, "-");
314 exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);