summaryrefslogtreecommitdiff
path: root/src/paste.c
blob: 264ed3d8e6db7c3a621fb9ea9283d654a286dda0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
/* paste - merge lines of files
   Copyright (C) 1984 by David M. Ihnat

   This program is a total rewrite of the Bell Laboratories Unix(Tm)
   command of the same name, as of System V.  It contains no proprietary
   code, and therefore may be used without violation of any proprietary
   agreements whatsoever.  However, you will notice that the program is
   copyrighted by me.  This is to assure the program does *not* fall
   into the public domain.  Thus, I may specify just what I am now:
   This program may be freely copied and distributed, provided this notice
   remains; it may not be sold for profit without express written consent of
   the author.
   Please note that I recreated the behavior of the Unix(Tm) 'paste' command
   as faithfully as possible, with minor exceptions; however,
   I haven't run a full set of regression tests.  Thus, the user of
   this program accepts full responsibility for any effects or loss;
   in particular, the author is not responsible for any losses,
   explicit or incidental, that may be incurred through use of this program.

   I ask that any bugs (and, if possible, fixes) be reported to me when
   possible.  -David Ihnat (312) 784-4544 ignatz@homebru.chi.il.us

   The list of valid escape sequences has been expanded over the Unix
   version, to include \b, \f, \r, and \v.

   POSIX changes, bug fixes, long-named options, and cleanup
   by David MacKenzie <djm@gnu.ai.mit.edu>.

   Options:
   --serial
   -s				Paste one file at a time rather than
				one line from each file.
   --delimiters=delim-list
   -d delim-list		Consecutively use the characters in
				DELIM-LIST instead of tab to separate
				merged lines.  When DELIM-LIST is exhausted,
				start again at its beginning.
   A FILE of `-' means standard input.
   If no FILEs are given, standard input is used. */

#include <config.h>

#include <stdio.h>
#include <getopt.h>
#include <sys/types.h>
#include "system.h"
#include "error.h"

char *xmalloc ();
char *xrealloc ();

/* Indicates that no delimiter should be added in the current position. */
#define EMPTY_DELIM '\0'

static FILE dummy_closed;
/* Element marking a file that has reached EOF and been closed. */
#define	CLOSED (&dummy_closed)

static FILE dummy_endlist;
/* Element marking end of list of open files. */
#define ENDLIST (&dummy_endlist)

/* Name this program was run with. */
char *program_name;

/* If nonzero, we have read standard input at some point. */
static int have_read_stdin;

/* If nonzero, merge subsequent lines of each file rather than
   corresponding lines from each file in parallel. */
static int serial_merge;

/* The delimeters between lines of input files (used cyclically). */
static char *delims;

/* A pointer to the character after the end of `delims'. */
static char *delim_end;

/* If nonzero, display usage information and exit.  */
static int show_help;

/* If nonzero, print the version on standard output then exit.  */
static int show_version;

static struct option const longopts[] =
{
  {"serial", no_argument, 0, 's'},
  {"delimiters", required_argument, 0, 'd'},
  {"help", no_argument, &show_help, 1},
  {"version", no_argument, &show_version, 1},
  {0, 0, 0, 0}
};

/* Replace backslash representations of special characters in
   STRPTR with their actual values.
   The set of possible backslash characters has been expanded beyond
   that recognized by the Unix version.

   Return a pointer to the character after the new end of STRPTR. */

static char *
collapse_escapes (char *strptr)
{
  register char *strout;

  strout = strptr;		/* Start at the same place, anyway. */

  while (*strptr)
    {
      if (*strptr != '\\')	/* Is it an escape character? */
	*strout++ = *strptr++;	/* No, just transfer it. */
      else
	{
	  switch (*++strptr)
	    {
	    case '0':
	      *strout++ = EMPTY_DELIM;
	      break;

	    case 'b':
	      *strout++ = '\b';
	      break;

	    case 'f':
	      *strout++ = '\f';
	      break;

	    case 'n':
	      *strout++ = '\n';
	      break;

	    case 'r':
	      *strout++ = '\r';
	      break;

	    case 't':
	      *strout++ = '\t';
	      break;

	    case 'v':
	      *strout++ = '\v';
	      break;

	    default:
	      *strout++ = *strptr;
	      break;
	    }
	  strptr++;
	}
    }
  return strout;
}

/* Perform column paste on the NFILES files named in FNAMPTR.
   Return 0 if no errors, 1 if one or more files could not be
   opened or read. */

static int
paste_parallel (int nfiles, char **fnamptr)
{
  int errors = 0;		/* 1 if open or read errors occur. */
  /* Number of files for which space is allocated in `delbuf' and `fileptr'.
     Enlarged as necessary. */
  int file_list_size = 12;
  int chr;			/* Input character. */
  int line_length;		/* Number of chars in line. */
  int somedone;			/* 0 if all files empty for this line. */
  /* If all files are just ready to be closed, or will be on this
     round, the string of delimiters must be preserved.
     delbuf[0] through delbuf[file_list_size]
     store the delimiters for closed files. */
  char *delbuf;
  int delims_saved;		/* Number of delims saved in `delbuf'. */
  register char *delimptr;	/* Cycling pointer into `delims'. */
  FILE **fileptr;		/* Streams open to the files to process. */
  int files_open;		/* Number of files still open to process. */
  int i;			/* Loop index. */
  int opened_stdin = 0;		/* Nonzero if any fopen got fd 0. */

#ifdef lint  /* Suppress `used before initialized' warning.  */
  chr = 0;
#endif

  delbuf = (char *) xmalloc (file_list_size + 2);
  fileptr = (FILE **) xmalloc ((file_list_size + 1) * sizeof (FILE *));

  /* Attempt to open all files.  This could be expanded to an infinite
     number of files, but at the (considerable) expense of remembering
     each file and its current offset, then opening/reading/closing.  */

  for (files_open = 0; files_open < nfiles; ++files_open)
    {
      if (files_open == file_list_size - 2)
	{
	  file_list_size += 12;
	  delbuf = (char *) xrealloc (delbuf, file_list_size + 2);
	  fileptr = (FILE **) xrealloc (fileptr, (file_list_size + 1)
					* sizeof (FILE *));
	}
      if (!strcmp (fnamptr[files_open], "-"))
	{
	  have_read_stdin = 1;
	  fileptr[files_open] = stdin;
	}
      else
	{
	  fileptr[files_open] = fopen (fnamptr[files_open], "r");
	  if (fileptr[files_open] == NULL)
	    error (EXIT_FAILURE, errno, "%s", fnamptr[files_open]);
	  else if (fileno (fileptr[files_open]) == 0)
	    opened_stdin = 1;
	}
    }

  fileptr[files_open] = ENDLIST;

  if (opened_stdin && have_read_stdin)
    error (EXIT_FAILURE, 0, _("standard input is closed"));

  /* Read a line from each file and output it to stdout separated by a
     delimiter, until we go through the loop without successfully
     reading from any of the files. */

  while (files_open)
    {
      /* Set up for the next line. */
      somedone = 0;
      delimptr = delims;
      delims_saved = 0;

      for (i = 0; fileptr[i] != ENDLIST && files_open; i++)
	{
	  line_length = 0;	/* Clear so we can easily detect EOF. */
	  if (fileptr[i] != CLOSED)
	    {
	      chr = getc (fileptr[i]);
	      if (chr != EOF && delims_saved)
		{
		  fwrite (delbuf, sizeof (char), delims_saved, stdout);
		  delims_saved = 0;
		}

	      while (chr != EOF)
		{
		  line_length++;
		  if (chr == '\n')
		    break;
		  putc (chr, stdout);
		  chr = getc (fileptr[i]);
		}
	    }

	  if (line_length == 0)
	    {
	      /* EOF, read error, or closed file.
		 If an EOF or error, close the file and mark it in the list. */
	      if (fileptr[i] != CLOSED)
		{
		  if (ferror (fileptr[i]))
		    {
		      error (0, errno, "%s", fnamptr[i]);
		      errors = 1;
		    }
		  if (fileptr[i] == stdin)
		    clearerr (fileptr[i]); /* Also clear EOF. */
		  else if (fclose (fileptr[i]) == EOF)
		    {
		      error (0, errno, "%s", fnamptr[i]);
		      errors = 1;
		    }

		  fileptr[i] = CLOSED;
		  files_open--;
		}

	      if (fileptr[i + 1] == ENDLIST)
		{
		  /* End of this output line.
		     Is this the end of the whole thing? */
		  if (somedone)
		    {
		      /* No.  Some files were not closed for this line. */
		      if (delims_saved)
			{
			  fwrite (delbuf, sizeof (char), delims_saved, stdout);
			  delims_saved = 0;
			}
		      putc ('\n', stdout);
		    }
		  continue;	/* Next read of files, or exit. */
		}
	      else
		{
		  /* Closed file; add delimiter to `delbuf'. */
		  if (*delimptr != EMPTY_DELIM)
		    delbuf[delims_saved++] = *delimptr;
		  if (++delimptr == delim_end)
		    delimptr = delims;
		}
	    }
	  else
	    {
	      /* Some data read. */
	      somedone++;

	      /* Except for last file, replace last newline with delim. */
	      if (fileptr[i + 1] != ENDLIST)
		{
		  if (chr != '\n')
		    putc (chr, stdout);
		  if (*delimptr != EMPTY_DELIM)
		    putc (*delimptr, stdout);
		  if (++delimptr == delim_end)
		    delimptr = delims;
		}
	      else
		putc (chr, stdout);
	    }
	}
    }
  return errors;
}

/* Perform serial paste on the NFILES files named in FNAMPTR.
   Return 0 if no errors, 1 if one or more files could not be
   opened or read. */

static int
paste_serial (int nfiles, char **fnamptr)
{
  int errors = 0;		/* 1 if open or read errors occur. */
  register int charnew, charold; /* Current and previous char read. */
  register char *delimptr;	/* Current delimiter char. */
  register FILE *fileptr;	/* Open for reading current file. */

  for (; nfiles; nfiles--, fnamptr++)
    {
      if (!strcmp (*fnamptr, "-"))
	{
	  have_read_stdin = 1;
	  fileptr = stdin;
	}
      else
	{
	  fileptr = fopen (*fnamptr, "r");
	  if (fileptr == NULL)
	    {
	      error (0, errno, "%s", *fnamptr);
	      errors = 1;
	      continue;
	    }
	}

      delimptr = delims;	/* Set up for delimiter string. */

      charold = getc (fileptr);
      if (charold != EOF)
	{
	  /* `charold' is set up.  Hit it!
	     Keep reading characters, stashing them in `charnew';
	     output `charold', converting to the appropriate delimiter
	     character if needed.  After the EOF, output `charold'
	     if it's a newline; otherwise, output it and then a newline. */

	  while ((charnew = getc (fileptr)) != EOF)
	    {
	      /* Process the old character. */
	      if (charold == '\n')
		{
		  if (*delimptr != EMPTY_DELIM)
		    putc (*delimptr, stdout);

		  if (++delimptr == delim_end)
		    delimptr = delims;
		}
	      else
		putc (charold, stdout);

	      charold = charnew;
	    }

	  /* Hit EOF.  Process that last character. */
	  putc (charold, stdout);
	}

      if (charold != '\n')
	putc ('\n', stdout);

      if (ferror (fileptr))
	{
	  error (0, errno, "%s", *fnamptr);
	  errors = 1;
	}
      if (fileptr == stdin)
	clearerr (fileptr);	/* Also clear EOF. */
      else if (fclose (fileptr) == EOF)
	{
	  error (0, errno, "%s", *fnamptr);
	  errors = 1;
	}
    }
  return errors;
}

static void
usage (int status)
{
  if (status != 0)
    fprintf (stderr, _("Try `%s --help' for more information.\n"),
	     program_name);
  else
    {
      printf (_("\
Usage: %s [OPTION]... [FILE]...\n\
"),
	      program_name);
      printf (_("\
Write lines consisting of the sequentially corresponding lines from\n\
each FILE, separated by TABs, to standard output.\n\
With no FILE, or when FILE is -, read standard input.\n\
\n\
  -d, --delimiters=LIST   reuse characters from LIST instead of TABs\n\
  -s, --serial            paste one file at a time instead of in parallel\n\
      --help              display this help and exit\n\
      --version           output version information and exit\n\
\n\
"));
      puts (_("\nReport bugs to <textutils-bugs@gnu.ai.mit.edu>."));
    }
  exit (status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
}

int
main (int argc, char **argv)
{
  int optc, exit_status;
  char default_delims[2], zero_delims[3];

  program_name = argv[0];
  setlocale (LC_ALL, "");
  bindtextdomain (PACKAGE, LOCALEDIR);
  textdomain (PACKAGE);

  have_read_stdin = 0;
  serial_merge = 0;
  delims = default_delims;
  strcpy (delims, "\t");
  strcpy (zero_delims, "\\0");

  while ((optc = getopt_long (argc, argv, "d:s", longopts, NULL)) != -1)
    {
      switch (optc)
	{
	case 0:
	  break;

	case 'd':
	  /* Delimiter character(s). */
	  if (optarg[0] == '\0')
	    optarg = zero_delims;
	  delims = optarg;
	  break;

	case 's':
	  serial_merge++;
	  break;

	default:
	  usage (1);
	}
    }

  if (show_version)
    {
      printf ("paste (%s) %s\n", GNU_PACKAGE, VERSION);
      exit (EXIT_SUCCESS);
    }

  if (show_help)
    usage (0);

  if (optind == argc)
    argv[argc++] = "-";

  delim_end = collapse_escapes (delims);

  if (!serial_merge)
    exit_status = paste_parallel (argc - optind, &argv[optind]);
  else
    exit_status = paste_serial (argc - optind, &argv[optind]);
  if (have_read_stdin && fclose (stdin) == EOF)
    error (EXIT_FAILURE, errno, "-");
  if (ferror (stdout) || fclose (stdout) == EOF)
    error (EXIT_FAILURE, errno, _("write error"));
  exit (exit_status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
}