version 8.7
[coreutils.git] / src / fold.c
blob4da834b17febde4e481294ddc12338ffe0a577e8
1 /* fold -- wrap each input line to fit in specified width.
2 Copyright (C) 1991, 1995-2006, 2008-2010 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 fprintf (stderr, _("Try `%s --help' for more information.\n"),
64 program_name);
65 else
67 printf (_("\
68 Usage: %s [OPTION]... [FILE]...\n\
69 "),
70 program_name);
71 fputs (_("\
72 Wrap input lines in each FILE (standard input by default), writing to\n\
73 standard output.\n\
74 \n\
75 "), stdout);
76 fputs (_("\
77 Mandatory arguments to long options are mandatory for short options too.\n\
78 "), stdout);
79 fputs (_("\
80 -b, --bytes count bytes rather than columns\n\
81 -s, --spaces break at spaces\n\
82 -w, --width=WIDTH use WIDTH columns instead of 80\n\
83 "), stdout);
84 fputs (HELP_OPTION_DESCRIPTION, stdout);
85 fputs (VERSION_OPTION_DESCRIPTION, stdout);
86 emit_ancillary_info ();
88 exit (status);
91 /* Assuming the current column is COLUMN, return the column that
92 printing C will move the cursor to.
93 The first column is 0. */
95 static size_t
96 adjust_column (size_t column, char c)
98 if (!count_bytes)
100 if (c == '\b')
102 if (column > 0)
103 column--;
105 else if (c == '\r')
106 column = 0;
107 else if (c == '\t')
108 column += TAB_WIDTH - column % TAB_WIDTH;
109 else /* if (isprint (c)) */
110 column++;
112 else
113 column++;
114 return column;
117 /* Fold file FILENAME, or standard input if FILENAME is "-",
118 to stdout, with maximum line length WIDTH.
119 Return true if successful. */
121 static bool
122 fold_file (char const *filename, size_t width)
124 FILE *istream;
125 int c;
126 size_t column = 0; /* Screen column where next char will go. */
127 size_t offset_out = 0; /* Index in `line_out' for next char. */
128 static char *line_out = NULL;
129 static size_t allocated_out = 0;
130 int saved_errno;
132 if (STREQ (filename, "-"))
134 istream = stdin;
135 have_read_stdin = true;
137 else
138 istream = fopen (filename, "r");
140 if (istream == NULL)
142 error (0, errno, "%s", filename);
143 return false;
146 fadvise (istream, FADVISE_SEQUENTIAL);
148 while ((c = getc (istream)) != EOF)
150 if (offset_out + 1 >= allocated_out)
151 line_out = X2REALLOC (line_out, &allocated_out);
153 if (c == '\n')
155 line_out[offset_out++] = c;
156 fwrite (line_out, sizeof (char), offset_out, stdout);
157 column = offset_out = 0;
158 continue;
161 rescan:
162 column = adjust_column (column, c);
164 if (column > width)
166 /* This character would make the line too long.
167 Print the line plus a newline, and make this character
168 start the next line. */
169 if (break_spaces)
171 bool found_blank = false;
172 size_t logical_end = offset_out;
174 /* Look for the last blank. */
175 while (logical_end)
177 --logical_end;
178 if (isblank (to_uchar (line_out[logical_end])))
180 found_blank = true;
181 break;
185 if (found_blank)
187 size_t i;
189 /* Found a blank. Don't output the part after it. */
190 logical_end++;
191 fwrite (line_out, sizeof (char), (size_t) logical_end,
192 stdout);
193 putchar ('\n');
194 /* Move the remainder to the beginning of the next line.
195 The areas being copied here might overlap. */
196 memmove (line_out, line_out + logical_end,
197 offset_out - logical_end);
198 offset_out -= logical_end;
199 for (column = i = 0; i < offset_out; i++)
200 column = adjust_column (column, line_out[i]);
201 goto rescan;
205 if (offset_out == 0)
207 line_out[offset_out++] = c;
208 continue;
211 line_out[offset_out++] = '\n';
212 fwrite (line_out, sizeof (char), (size_t) offset_out, stdout);
213 column = offset_out = 0;
214 goto rescan;
217 line_out[offset_out++] = c;
220 saved_errno = errno;
222 if (offset_out)
223 fwrite (line_out, sizeof (char), (size_t) offset_out, stdout);
225 if (ferror (istream))
227 error (0, saved_errno, "%s", filename);
228 if (!STREQ (filename, "-"))
229 fclose (istream);
230 return false;
232 if (!STREQ (filename, "-") && fclose (istream) == EOF)
234 error (0, errno, "%s", filename);
235 return false;
238 return true;
242 main (int argc, char **argv)
244 size_t width = 80;
245 int i;
246 int optc;
247 bool ok;
249 initialize_main (&argc, &argv);
250 set_program_name (argv[0]);
251 setlocale (LC_ALL, "");
252 bindtextdomain (PACKAGE, LOCALEDIR);
253 textdomain (PACKAGE);
255 atexit (close_stdout);
257 break_spaces = count_bytes = have_read_stdin = false;
259 while ((optc = getopt_long (argc, argv, shortopts, longopts, NULL)) != -1)
261 char optargbuf[2];
263 switch (optc)
265 case 'b': /* Count bytes rather than columns. */
266 count_bytes = true;
267 break;
269 case 's': /* Break at word boundaries. */
270 break_spaces = true;
271 break;
273 case '0': case '1': case '2': case '3': case '4':
274 case '5': case '6': case '7': case '8': case '9':
275 if (optarg)
276 optarg--;
277 else
279 optargbuf[0] = optc;
280 optargbuf[1] = '\0';
281 optarg = optargbuf;
283 /* Fall through. */
284 case 'w': /* Line width. */
286 unsigned long int tmp_ulong;
287 if (! (xstrtoul (optarg, NULL, 10, &tmp_ulong, "") == LONGINT_OK
288 && 0 < tmp_ulong && tmp_ulong < SIZE_MAX - TAB_WIDTH))
289 error (EXIT_FAILURE, 0,
290 _("invalid number of columns: %s"), quote (optarg));
291 width = tmp_ulong;
293 break;
295 case_GETOPT_HELP_CHAR;
297 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
299 default:
300 usage (EXIT_FAILURE);
304 if (argc == optind)
305 ok = fold_file ("-", width);
306 else
308 ok = true;
309 for (i = optind; i < argc; i++)
310 ok &= fold_file (argv[i], width);
313 if (have_read_stdin && fclose (stdin) == EOF)
314 error (EXIT_FAILURE, errno, "-");
316 exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);