*** empty log message ***
[coreutils.git] / src / fold.c
blobbe1d669da37bb0aa562d62d91151998be2a8cc95
1 /* fold -- wrap each input line to fit in specified width.
2 Copyright (C) 91, 1995-2002 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 Foundation,
16 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 #include <stdio.h>
23 #include <getopt.h>
24 #include <sys/types.h>
26 #include "system.h"
27 #include "closeout.h"
28 #include "error.h"
29 #include "posixver.h"
30 #include "xstrtol.h"
32 /* The official name of this program (e.g., no `g' prefix). */
33 #define PROGRAM_NAME "fold"
35 #define AUTHORS "David MacKenzie"
37 /* The name this program was run with. */
38 char *program_name;
40 /* If nonzero, try to break on whitespace. */
41 static int break_spaces;
43 /* If nonzero, count bytes, not column positions. */
44 static int count_bytes;
46 /* If nonzero, at least one of the files we read was standard input. */
47 static int have_read_stdin;
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 != 0)
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 printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
88 exit (status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
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 int
96 adjust_column (int 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 = column + 8 - column % 8;
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 0 if successful, 1 if an error occurs. */
121 static int
122 fold_file (char *filename, int width)
124 FILE *istream;
125 register int c;
126 int column = 0; /* Screen column where next char will go. */
127 int offset_out = 0; /* Index in `line_out' for next char. */
128 static char *line_out = NULL;
129 static int allocated_out = 0;
131 if (STREQ (filename, "-"))
133 istream = stdin;
134 have_read_stdin = 1;
136 else
137 istream = fopen (filename, "r");
139 if (istream == NULL)
141 error (0, errno, "%s", filename);
142 return 1;
145 while ((c = getc (istream)) != EOF)
147 if (offset_out + 1 >= allocated_out)
149 allocated_out += 1024;
150 line_out = xrealloc (line_out, allocated_out);
153 if (c == '\n')
155 line_out[offset_out++] = c;
156 fwrite (line_out, sizeof (char), (size_t) 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 /* Look for the last blank. */
172 int logical_end;
174 for (logical_end = offset_out - 1; logical_end >= 0;
175 logical_end--)
176 if (ISBLANK (line_out[logical_end]))
177 break;
178 if (logical_end >= 0)
180 int i;
182 /* Found a blank. Don't output the part after it. */
183 logical_end++;
184 fwrite (line_out, sizeof (char), (size_t) logical_end,
185 stdout);
186 putchar ('\n');
187 /* Move the remainder to the beginning of the next line.
188 The areas being copied here might overlap. */
189 memmove (line_out, line_out + logical_end,
190 offset_out - logical_end);
191 offset_out -= logical_end;
192 for (column = i = 0; i < offset_out; i++)
193 column = adjust_column (column, line_out[i]);
194 goto rescan;
197 else
199 if (offset_out == 0)
201 line_out[offset_out++] = c;
202 continue;
205 line_out[offset_out++] = '\n';
206 fwrite (line_out, sizeof (char), (size_t) offset_out, stdout);
207 column = offset_out = 0;
208 goto rescan;
211 line_out[offset_out++] = c;
214 if (offset_out)
215 fwrite (line_out, sizeof (char), (size_t) offset_out, stdout);
217 if (ferror (istream))
219 error (0, errno, "%s", filename);
220 if (!STREQ (filename, "-"))
221 fclose (istream);
222 return 1;
224 if (!STREQ (filename, "-") && fclose (istream) == EOF)
226 error (0, errno, "%s", filename);
227 return 1;
230 return 0;
234 main (int argc, char **argv)
236 int width = 80;
237 int i;
238 int optc;
239 int errs = 0;
241 program_name = argv[0];
242 setlocale (LC_ALL, "");
243 bindtextdomain (PACKAGE, LOCALEDIR);
244 textdomain (PACKAGE);
246 atexit (close_stdout);
248 break_spaces = count_bytes = have_read_stdin = 0;
250 /* Turn any numeric options into -w options. */
251 for (i = 1; i < argc; i++)
253 char const *a = argv[i];
254 if (a[0] == '-')
256 if (a[1] == '-' && ! a[2])
257 break;
258 if (ISDIGIT (a[1]))
260 char *s = xmalloc (strlen (a) + 2);
261 s[0] = '-';
262 s[1] = 'w';
263 strcpy (s + 2, a + 1);
264 argv[i] = s;
265 if (200112 <= posix2_version ())
267 error (0, 0, _("`%s' option is obsolete; use `%s'"), a, s);
268 usage (EXIT_FAILURE);
274 while ((optc = getopt_long (argc, argv, "bsw:", longopts, NULL)) != -1)
276 switch (optc)
278 case 0:
279 break;
281 case 'b': /* Count bytes rather than columns. */
282 count_bytes = 1;
283 break;
285 case 's': /* Break at word boundaries. */
286 break_spaces = 1;
287 break;
289 case 'w': /* Line width. */
291 long int tmp_long;
292 if (xstrtol (optarg, NULL, 10, &tmp_long, "") != LONGINT_OK
293 || tmp_long <= 0 || tmp_long > INT_MAX)
294 error (EXIT_FAILURE, 0,
295 _("invalid number of columns: `%s'"), optarg);
296 width = (int) tmp_long;
298 break;
300 case_GETOPT_HELP_CHAR;
302 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
304 default:
305 usage (1);
309 if (argc == optind)
310 errs |= fold_file ("-", width);
311 else
312 for (i = optind; i < argc; i++)
313 errs |= fold_file (argv[i], width);
315 if (have_read_stdin && fclose (stdin) == EOF)
316 error (EXIT_FAILURE, errno, "-");
318 exit (errs == 0 ? EXIT_SUCCESS : EXIT_FAILURE);