.
[coreutils.git] / src / fold.c
bloba23b637c85dec613eceac897c195e3921e9363c9
1 /* fold -- wrap each input line to fit in specified width.
2 Copyright (C) 1991, 1995 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 2, or (at your option)
7 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, write to the Free Software
16 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
18 /* Written by David MacKenzie, djm@gnu.ai.mit.edu. */
20 #include <config.h>
22 /* Get isblank from GNU libc. */
23 #define _GNU_SOURCE
25 #include <stdio.h>
26 #include <getopt.h>
27 #include <sys/types.h>
29 #if HAVE_LIMITS_H
30 # include <limits.h>
31 #endif
33 #ifndef UINT_MAX
34 # define UINT_MAX ((unsigned int) ~(unsigned int) 0)
35 #endif
37 #ifndef INT_MAX
38 # define INT_MAX ((int) (UINT_MAX >> 1))
39 #endif
41 #include "system.h"
42 #include "version.h"
43 #include "xstrtol.h"
44 #include "error.h"
46 char *xrealloc ();
47 char *xmalloc ();
49 /* The name this program was run with. */
50 char *program_name;
52 /* If nonzero, try to break on whitespace. */
53 static int break_spaces;
55 /* If nonzero, count bytes, not column positions. */
56 static int count_bytes;
58 /* If nonzero, at least one of the files we read was standard input. */
59 static int have_read_stdin;
61 /* If nonzero, display usage information and exit. */
62 static int show_help;
64 /* If nonzero, print the version on standard output then exit. */
65 static int show_version;
67 static struct option const longopts[] =
69 {"bytes", no_argument, NULL, 'b'},
70 {"spaces", no_argument, NULL, 's'},
71 {"width", required_argument, NULL, 'w'},
72 {"help", no_argument, &show_help, 1},
73 {"version", no_argument, &show_version, 1},
74 {NULL, 0, NULL, 0}
77 static void
78 usage (int status)
80 if (status != 0)
81 fprintf (stderr, _("Try `%s --help' for more information.\n"),
82 program_name);
83 else
85 printf (_("\
86 Usage: %s [OPTION]... [FILE]...\n\
87 "),
88 program_name);
89 printf (_("\
90 Wrap input lines in each FILE (standard input by default), writing to\n\
91 standard output.\n\
92 \n\
93 -b, --bytes count bytes rather than columns\n\
94 -s, --spaces break at spaces\n\
95 -w, --width=WIDTH use WIDTH columns instead of 80\n\
96 "));
98 exit (status);
101 /* Assuming the current column is COLUMN, return the column that
102 printing C will move the cursor to.
103 The first column is 0. */
105 static int
106 adjust_column (int column, char c)
108 if (!count_bytes)
110 if (c == '\b')
112 if (column > 0)
113 column--;
115 else if (c == '\r')
116 column = 0;
117 else if (c == '\t')
118 column = column + 8 - column % 8;
119 else /* if (isprint (c)) */
120 column++;
122 else
123 column++;
124 return column;
127 /* Fold file FILENAME, or standard input if FILENAME is "-",
128 to stdout, with maximum line length WIDTH.
129 Return 0 if successful, 1 if an error occurs. */
131 static int
132 fold_file (char *filename, int width)
134 FILE *istream;
135 register int c;
136 int column = 0; /* Screen column where next char will go. */
137 int offset_out = 0; /* Index in `line_out' for next char. */
138 static char *line_out = NULL;
139 static int allocated_out = 0;
141 if (!strcmp (filename, "-"))
143 istream = stdin;
144 have_read_stdin = 1;
146 else
147 istream = fopen (filename, "r");
149 if (istream == NULL)
151 error (0, errno, "%s", filename);
152 return 1;
155 while ((c = getc (istream)) != EOF)
157 if (offset_out + 1 >= allocated_out)
159 allocated_out += 1024;
160 line_out = xrealloc (line_out, allocated_out);
163 if (c == '\n')
165 line_out[offset_out++] = c;
166 fwrite (line_out, sizeof (char), (size_t) offset_out, stdout);
167 column = offset_out = 0;
168 continue;
171 rescan:
172 column = adjust_column (column, c);
174 if (column > width)
176 /* This character would make the line too long.
177 Print the line plus a newline, and make this character
178 start the next line. */
179 if (break_spaces)
181 /* Look for the last blank. */
182 int logical_end;
184 for (logical_end = offset_out - 1; logical_end >= 0;
185 logical_end--)
186 if (ISBLANK (line_out[logical_end]))
187 break;
188 if (logical_end >= 0)
190 int i;
192 /* Found a blank. Don't output the part after it. */
193 logical_end++;
194 fwrite (line_out, sizeof (char), (size_t) logical_end,
195 stdout);
196 putchar ('\n');
197 /* Move the remainder to the beginning of the next line.
198 The areas being copied here might overlap. */
199 memmove (line_out, line_out + logical_end,
200 offset_out - logical_end);
201 offset_out -= logical_end;
202 for (column = i = 0; i < offset_out; i++)
203 column = adjust_column (column, line_out[i]);
204 goto rescan;
207 else
209 if (offset_out == 0)
211 line_out[offset_out++] = c;
212 continue;
215 line_out[offset_out++] = '\n';
216 fwrite (line_out, sizeof (char), (size_t) offset_out, stdout);
217 column = offset_out = 0;
218 goto rescan;
221 line_out[offset_out++] = c;
224 if (offset_out)
225 fwrite (line_out, sizeof (char), (size_t) offset_out, stdout);
227 if (ferror (istream))
229 error (0, errno, "%s", filename);
230 if (strcmp (filename, "-"))
231 fclose (istream);
232 return 1;
234 if (strcmp (filename, "-") && fclose (istream) == EOF)
236 error (0, errno, "%s", filename);
237 return 1;
240 if (ferror (stdout))
242 error (0, errno, _("write error"));
243 return 1;
246 return 0;
249 void
250 main (int argc, char **argv)
252 int width = 80;
253 int i;
254 int optc;
255 int errs = 0;
257 program_name = argv[0];
258 setlocale (LC_ALL, "");
259 bindtextdomain (PACKAGE, LOCALEDIR);
260 textdomain (PACKAGE);
262 break_spaces = count_bytes = have_read_stdin = 0;
264 /* Turn any numeric options into -w options. */
265 for (i = 1; i < argc; i++)
267 if (argv[i][0] == '-' && ISDIGIT (argv[i][1]))
269 char *s;
271 s = xmalloc (strlen (argv[i]) + 2);
272 s[0] = '-';
273 s[1] = 'w';
274 strcpy (s + 2, argv[i] + 1);
275 argv[i] = s;
279 while ((optc = getopt_long (argc, argv, "bsw:", longopts, (int *) 0))
280 != EOF)
282 switch (optc)
284 case 0:
285 break;
287 case 'b': /* Count bytes rather than columns. */
288 count_bytes = 1;
289 break;
291 case 's': /* Break at word boundaries. */
292 break_spaces = 1;
293 break;
295 case 'w': /* Line width. */
297 long int tmp_long;
298 if (xstrtol (optarg, NULL, 10, &tmp_long, NULL) != LONGINT_OK
299 || tmp_long <= 0 || tmp_long > INT_MAX)
300 error (1, 0, _("invalid number of columns: `%s'"), optarg);
301 width = (int) tmp_long;
303 break;
305 default:
306 usage (1);
310 if (show_version)
312 printf ("fold - %s\n", version_string);
313 exit (0);
316 if (show_help)
317 usage (0);
319 if (argc == optind)
320 errs |= fold_file ("-", width);
321 else
322 for (i = optind; i < argc; i++)
323 errs |= fold_file (argv[i], width);
325 if (have_read_stdin && fclose (stdin) == EOF)
326 error (1, errno, "-");
327 if (fclose (stdout) == EOF)
328 error (1, errno, _("write error"));
330 exit (errs);