PageRenderTime 44ms CodeModel.GetById 10ms RepoModel.GetById 1ms app.codeStats 0ms

/c/coreutils-7.4/src/tac.c

http://timoseven.googlecode.com/
C | 666 lines | 447 code | 93 blank | 126 comment | 86 complexity | 91bbe9510a7aa0a3d581d319aff1663d MD5 | raw file
Possible License(s): MIT, LGPL-2.1, MPL-2.0-no-copyleft-exception, GPL-3.0, AGPL-1.0
  1. /* tac - concatenate and print files in reverse
  2. Copyright (C) 1988-1991, 1995-2006, 2008 Free Software Foundation, Inc.
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation, either version 3 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>. */
  13. /* Written by Jay Lepreau (lepreau@cs.utah.edu).
  14. GNU enhancements by David MacKenzie (djm@gnu.ai.mit.edu). */
  15. /* Copy each FILE, or the standard input if none are given or when a
  16. FILE name of "-" is encountered, to the standard output with the
  17. order of the records reversed. The records are separated by
  18. instances of a string, or a newline if none is given. By default, the
  19. separator string is attached to the end of the record that it
  20. follows in the file.
  21. Options:
  22. -b, --before The separator is attached to the beginning
  23. of the record that it precedes in the file.
  24. -r, --regex The separator is a regular expression.
  25. -s, --separator=separator Use SEPARATOR as the record separator.
  26. To reverse a file byte by byte, use (in bash, ksh, or sh):
  27. tac -r -s '.\|
  28. ' file */
  29. #include <config.h>
  30. #include <stdio.h>
  31. #include <getopt.h>
  32. #include <sys/types.h>
  33. #include "system.h"
  34. #include <regex.h>
  35. #include "error.h"
  36. #include "quote.h"
  37. #include "quotearg.h"
  38. #include "safe-read.h"
  39. #include "stdlib--.h"
  40. #include "xfreopen.h"
  41. /* The official name of this program (e.g., no `g' prefix). */
  42. #define PROGRAM_NAME "tac"
  43. #define AUTHORS \
  44. proper_name ("Jay Lepreau"), \
  45. proper_name ("David MacKenzie")
  46. #if defined __MSDOS__ || defined _WIN32
  47. /* Define this to non-zero on systems for which the regular mechanism
  48. (of unlinking an open file and expecting to be able to write, seek
  49. back to the beginning, then reread it) doesn't work. E.g., on Windows
  50. and DOS systems. */
  51. # define DONT_UNLINK_WHILE_OPEN 1
  52. #endif
  53. #ifndef DEFAULT_TMPDIR
  54. # define DEFAULT_TMPDIR "/tmp"
  55. #endif
  56. /* The number of bytes per atomic read. */
  57. #define INITIAL_READSIZE 8192
  58. /* The number of bytes per atomic write. */
  59. #define WRITESIZE 8192
  60. /* The string that separates the records of the file. */
  61. static char const *separator;
  62. /* True if we have ever read standard input. */
  63. static bool have_read_stdin = false;
  64. /* If true, print `separator' along with the record preceding it
  65. in the file; otherwise with the record following it. */
  66. static bool separator_ends_record;
  67. /* 0 if `separator' is to be matched as a regular expression;
  68. otherwise, the length of `separator', used as a sentinel to
  69. stop the search. */
  70. static size_t sentinel_length;
  71. /* The length of a match with `separator'. If `sentinel_length' is 0,
  72. `match_length' is computed every time a match succeeds;
  73. otherwise, it is simply the length of `separator'. */
  74. static size_t match_length;
  75. /* The input buffer. */
  76. static char *G_buffer;
  77. /* The number of bytes to read at once into `buffer'. */
  78. static size_t read_size;
  79. /* The size of `buffer'. This is read_size * 2 + sentinel_length + 2.
  80. The extra 2 bytes allow `past_end' to have a value beyond the
  81. end of `G_buffer' and `match_start' to run off the front of `G_buffer'. */
  82. static size_t G_buffer_size;
  83. /* The compiled regular expression representing `separator'. */
  84. static struct re_pattern_buffer compiled_separator;
  85. static char compiled_separator_fastmap[UCHAR_MAX + 1];
  86. static struct re_registers regs;
  87. static struct option const longopts[] =
  88. {
  89. {"before", no_argument, NULL, 'b'},
  90. {"regex", no_argument, NULL, 'r'},
  91. {"separator", required_argument, NULL, 's'},
  92. {GETOPT_HELP_OPTION_DECL},
  93. {GETOPT_VERSION_OPTION_DECL},
  94. {NULL, 0, NULL, 0}
  95. };
  96. void
  97. usage (int status)
  98. {
  99. if (status != EXIT_SUCCESS)
  100. fprintf (stderr, _("Try `%s --help' for more information.\n"),
  101. program_name);
  102. else
  103. {
  104. printf (_("\
  105. Usage: %s [OPTION]... [FILE]...\n\
  106. "),
  107. program_name);
  108. fputs (_("\
  109. Write each FILE to standard output, last line first.\n\
  110. With no FILE, or when FILE is -, read standard input.\n\
  111. \n\
  112. "), stdout);
  113. fputs (_("\
  114. Mandatory arguments to long options are mandatory for short options too.\n\
  115. "), stdout);
  116. fputs (_("\
  117. -b, --before attach the separator before instead of after\n\
  118. -r, --regex interpret the separator as a regular expression\n\
  119. -s, --separator=STRING use STRING as the separator instead of newline\n\
  120. "), stdout);
  121. fputs (HELP_OPTION_DESCRIPTION, stdout);
  122. fputs (VERSION_OPTION_DESCRIPTION, stdout);
  123. emit_bug_reporting_address ();
  124. }
  125. exit (status);
  126. }
  127. /* Print the characters from START to PAST_END - 1.
  128. If START is NULL, just flush the buffer. */
  129. static void
  130. output (const char *start, const char *past_end)
  131. {
  132. static char buffer[WRITESIZE];
  133. static size_t bytes_in_buffer = 0;
  134. size_t bytes_to_add = past_end - start;
  135. size_t bytes_available = WRITESIZE - bytes_in_buffer;
  136. if (start == 0)
  137. {
  138. fwrite (buffer, 1, bytes_in_buffer, stdout);
  139. bytes_in_buffer = 0;
  140. return;
  141. }
  142. /* Write out as many full buffers as possible. */
  143. while (bytes_to_add >= bytes_available)
  144. {
  145. memcpy (buffer + bytes_in_buffer, start, bytes_available);
  146. bytes_to_add -= bytes_available;
  147. start += bytes_available;
  148. fwrite (buffer, 1, WRITESIZE, stdout);
  149. bytes_in_buffer = 0;
  150. bytes_available = WRITESIZE;
  151. }
  152. memcpy (buffer + bytes_in_buffer, start, bytes_to_add);
  153. bytes_in_buffer += bytes_to_add;
  154. }
  155. /* Print in reverse the file open on descriptor FD for reading FILE.
  156. Return true if successful. */
  157. static bool
  158. tac_seekable (int input_fd, const char *file)
  159. {
  160. /* Pointer to the location in `G_buffer' where the search for
  161. the next separator will begin. */
  162. char *match_start;
  163. /* Pointer to one past the rightmost character in `G_buffer' that
  164. has not been printed yet. */
  165. char *past_end;
  166. /* Length of the record growing in `G_buffer'. */
  167. size_t saved_record_size;
  168. /* Offset in the file of the next read. */
  169. off_t file_pos;
  170. /* True if `output' has not been called yet for any file.
  171. Only used when the separator is attached to the preceding record. */
  172. bool first_time = true;
  173. char first_char = *separator; /* Speed optimization, non-regexp. */
  174. char const *separator1 = separator + 1; /* Speed optimization, non-regexp. */
  175. size_t match_length1 = match_length - 1; /* Speed optimization, non-regexp. */
  176. /* Find the size of the input file. */
  177. file_pos = lseek (input_fd, (off_t) 0, SEEK_END);
  178. if (file_pos < 1)
  179. return true; /* It's an empty file. */
  180. /* Arrange for the first read to lop off enough to leave the rest of the
  181. file a multiple of `read_size'. Since `read_size' can change, this may
  182. not always hold during the program run, but since it usually will, leave
  183. it here for i/o efficiency (page/sector boundaries and all that).
  184. Note: the efficiency gain has not been verified. */
  185. saved_record_size = file_pos % read_size;
  186. if (saved_record_size == 0)
  187. saved_record_size = read_size;
  188. file_pos -= saved_record_size;
  189. /* `file_pos' now points to the start of the last (probably partial) block
  190. in the input file. */
  191. if (lseek (input_fd, file_pos, SEEK_SET) < 0)
  192. error (0, errno, _("%s: seek failed"), quotearg_colon (file));
  193. if (safe_read (input_fd, G_buffer, saved_record_size) != saved_record_size)
  194. {
  195. error (0, errno, _("%s: read error"), quotearg_colon (file));
  196. return false;
  197. }
  198. match_start = past_end = G_buffer + saved_record_size;
  199. /* For non-regexp search, move past impossible positions for a match. */
  200. if (sentinel_length)
  201. match_start -= match_length1;
  202. for (;;)
  203. {
  204. /* Search backward from `match_start' - 1 to `G_buffer' for a match
  205. with `separator'; for speed, use strncmp if `separator' contains no
  206. metacharacters.
  207. If the match succeeds, set `match_start' to point to the start of
  208. the match and `match_length' to the length of the match.
  209. Otherwise, make `match_start' < `G_buffer'. */
  210. if (sentinel_length == 0)
  211. {
  212. size_t i = match_start - G_buffer;
  213. regoff_t ri = i;
  214. regoff_t range = 1 - ri;
  215. regoff_t ret;
  216. if (1 < range)
  217. error (EXIT_FAILURE, 0, _("record too large"));
  218. if (range == 1
  219. || ((ret = re_search (&compiled_separator, G_buffer,
  220. i, i - 1, range, &regs))
  221. == -1))
  222. match_start = G_buffer - 1;
  223. else if (ret == -2)
  224. {
  225. error (EXIT_FAILURE, 0,
  226. _("error in regular expression search"));
  227. }
  228. else
  229. {
  230. match_start = G_buffer + regs.start[0];
  231. match_length = regs.end[0] - regs.start[0];
  232. }
  233. }
  234. else
  235. {
  236. /* `match_length' is constant for non-regexp boundaries. */
  237. while (*--match_start != first_char
  238. || (match_length1 && strncmp (match_start + 1, separator1,
  239. match_length1)))
  240. /* Do nothing. */ ;
  241. }
  242. /* Check whether we backed off the front of `G_buffer' without finding
  243. a match for `separator'. */
  244. if (match_start < G_buffer)
  245. {
  246. if (file_pos == 0)
  247. {
  248. /* Hit the beginning of the file; print the remaining record. */
  249. output (G_buffer, past_end);
  250. return true;
  251. }
  252. saved_record_size = past_end - G_buffer;
  253. if (saved_record_size > read_size)
  254. {
  255. /* `G_buffer_size' is about twice `read_size', so since
  256. we want to read in another `read_size' bytes before
  257. the data already in `G_buffer', we need to increase
  258. `G_buffer_size'. */
  259. char *newbuffer;
  260. size_t offset = sentinel_length ? sentinel_length : 1;
  261. ptrdiff_t match_start_offset = match_start - G_buffer;
  262. ptrdiff_t past_end_offset = past_end - G_buffer;
  263. size_t old_G_buffer_size = G_buffer_size;
  264. read_size *= 2;
  265. G_buffer_size = read_size * 2 + sentinel_length + 2;
  266. if (G_buffer_size < old_G_buffer_size)
  267. xalloc_die ();
  268. newbuffer = xrealloc (G_buffer - offset, G_buffer_size);
  269. newbuffer += offset;
  270. /* Adjust the pointers for the new buffer location. */
  271. match_start = newbuffer + match_start_offset;
  272. past_end = newbuffer + past_end_offset;
  273. G_buffer = newbuffer;
  274. }
  275. /* Back up to the start of the next bufferfull of the file. */
  276. if (file_pos >= read_size)
  277. file_pos -= read_size;
  278. else
  279. {
  280. read_size = file_pos;
  281. file_pos = 0;
  282. }
  283. if (lseek (input_fd, file_pos, SEEK_SET) < 0)
  284. error (0, errno, _("%s: seek failed"), quotearg_colon (file));
  285. /* Shift the pending record data right to make room for the new.
  286. The source and destination regions probably overlap. */
  287. memmove (G_buffer + read_size, G_buffer, saved_record_size);
  288. past_end = G_buffer + read_size + saved_record_size;
  289. /* For non-regexp searches, avoid unneccessary scanning. */
  290. if (sentinel_length)
  291. match_start = G_buffer + read_size;
  292. else
  293. match_start = past_end;
  294. if (safe_read (input_fd, G_buffer, read_size) != read_size)
  295. {
  296. error (0, errno, _("%s: read error"), quotearg_colon (file));
  297. return false;
  298. }
  299. }
  300. else
  301. {
  302. /* Found a match of `separator'. */
  303. if (separator_ends_record)
  304. {
  305. char *match_end = match_start + match_length;
  306. /* If this match of `separator' isn't at the end of the
  307. file, print the record. */
  308. if (!first_time || match_end != past_end)
  309. output (match_end, past_end);
  310. past_end = match_end;
  311. first_time = false;
  312. }
  313. else
  314. {
  315. output (match_start, past_end);
  316. past_end = match_start;
  317. }
  318. /* For non-regex matching, we can back up. */
  319. if (sentinel_length > 0)
  320. match_start -= match_length - 1;
  321. }
  322. }
  323. }
  324. #if DONT_UNLINK_WHILE_OPEN
  325. /* FIXME-someday: remove all of this DONT_UNLINK_WHILE_OPEN junk.
  326. Using atexit like this is wrong, since it can fail
  327. when called e.g. 32 or more times.
  328. But this isn't a big deal, since the code is used only on WOE/DOS
  329. systems, and few people invoke tac on that many nonseekable files. */
  330. static const char *file_to_remove;
  331. static FILE *fp_to_close;
  332. static void
  333. unlink_tempfile (void)
  334. {
  335. fclose (fp_to_close);
  336. unlink (file_to_remove);
  337. }
  338. static void
  339. record_or_unlink_tempfile (char const *fn, FILE *fp)
  340. {
  341. if (!file_to_remove)
  342. {
  343. file_to_remove = fn;
  344. fp_to_close = fp;
  345. atexit (unlink_tempfile);
  346. }
  347. }
  348. #else
  349. static void
  350. record_or_unlink_tempfile (char const *fn, FILE *fp ATTRIBUTE_UNUSED)
  351. {
  352. unlink (fn);
  353. }
  354. #endif
  355. /* Copy from file descriptor INPUT_FD (corresponding to the named FILE) to
  356. a temporary file, and set *G_TMP and *G_TEMPFILE to the resulting stream
  357. and file name. Return true if successful. */
  358. static bool
  359. copy_to_temp (FILE **g_tmp, char **g_tempfile, int input_fd, char const *file)
  360. {
  361. static char *template = NULL;
  362. static char const *tempdir;
  363. char *tempfile;
  364. FILE *tmp;
  365. int fd;
  366. if (template == NULL)
  367. {
  368. char const * const Template = "%s/tacXXXXXX";
  369. tempdir = getenv ("TMPDIR");
  370. if (tempdir == NULL)
  371. tempdir = DEFAULT_TMPDIR;
  372. /* Subtract 2 for `%s' and add 1 for the trailing NUL byte. */
  373. template = xmalloc (strlen (tempdir) + strlen (Template) - 2 + 1);
  374. sprintf (template, Template, tempdir);
  375. }
  376. /* FIXME: there's a small window between a successful mkstemp call
  377. and the unlink that's performed by record_or_unlink_tempfile.
  378. If we're interrupted in that interval, this code fails to remove
  379. the temporary file. On systems that define DONT_UNLINK_WHILE_OPEN,
  380. the window is much larger -- it extends to the atexit-called
  381. unlink_tempfile.
  382. FIXME: clean up upon fatal signal. Don't block them, in case
  383. $TMPFILE is a remote file system. */
  384. tempfile = template;
  385. fd = mkstemp (template);
  386. if (fd < 0)
  387. {
  388. error (0, errno, _("cannot create temporary file in %s"),
  389. quote (tempdir));
  390. return false;
  391. }
  392. tmp = fdopen (fd, (O_BINARY ? "w+b" : "w+"));
  393. if (! tmp)
  394. {
  395. error (0, errno, _("cannot open %s for writing"), quote (tempfile));
  396. close (fd);
  397. unlink (tempfile);
  398. return false;
  399. }
  400. record_or_unlink_tempfile (tempfile, tmp);
  401. while (1)
  402. {
  403. size_t bytes_read = safe_read (input_fd, G_buffer, read_size);
  404. if (bytes_read == 0)
  405. break;
  406. if (bytes_read == SAFE_READ_ERROR)
  407. {
  408. error (0, errno, _("%s: read error"), quotearg_colon (file));
  409. goto Fail;
  410. }
  411. if (fwrite (G_buffer, 1, bytes_read, tmp) != bytes_read)
  412. {
  413. error (0, errno, _("%s: write error"), quotearg_colon (tempfile));
  414. goto Fail;
  415. }
  416. }
  417. if (fflush (tmp) != 0)
  418. {
  419. error (0, errno, _("%s: write error"), quotearg_colon (tempfile));
  420. goto Fail;
  421. }
  422. *g_tmp = tmp;
  423. *g_tempfile = tempfile;
  424. return true;
  425. Fail:
  426. fclose (tmp);
  427. return false;
  428. }
  429. /* Copy INPUT_FD to a temporary, then tac that file.
  430. Return true if successful. */
  431. static bool
  432. tac_nonseekable (int input_fd, const char *file)
  433. {
  434. FILE *tmp_stream;
  435. char *tmp_file;
  436. return (copy_to_temp (&tmp_stream, &tmp_file, input_fd, file)
  437. && tac_seekable (fileno (tmp_stream), tmp_file));
  438. }
  439. /* Print FILE in reverse, copying it to a temporary
  440. file first if it is not seekable.
  441. Return true if successful. */
  442. static bool
  443. tac_file (const char *filename)
  444. {
  445. bool ok;
  446. off_t file_size;
  447. int fd;
  448. bool is_stdin = STREQ (filename, "-");
  449. if (is_stdin)
  450. {
  451. have_read_stdin = true;
  452. fd = STDIN_FILENO;
  453. filename = _("standard input");
  454. if (O_BINARY && ! isatty (STDIN_FILENO))
  455. xfreopen (NULL, "rb", stdin);
  456. }
  457. else
  458. {
  459. fd = open (filename, O_RDONLY | O_BINARY);
  460. if (fd < 0)
  461. {
  462. error (0, errno, _("cannot open %s for reading"), quote (filename));
  463. return false;
  464. }
  465. }
  466. file_size = lseek (fd, (off_t) 0, SEEK_END);
  467. ok = (file_size < 0 || isatty (fd)
  468. ? tac_nonseekable (fd, filename)
  469. : tac_seekable (fd, filename));
  470. if (!is_stdin && close (fd) != 0)
  471. {
  472. error (0, errno, _("%s: read error"), quotearg_colon (filename));
  473. ok = false;
  474. }
  475. return ok;
  476. }
  477. int
  478. main (int argc, char **argv)
  479. {
  480. const char *error_message; /* Return value from re_compile_pattern. */
  481. int optc;
  482. bool ok;
  483. size_t half_buffer_size;
  484. /* Initializer for file_list if no file-arguments
  485. were specified on the command line. */
  486. static char const *const default_file_list[] = {"-", NULL};
  487. char const *const *file;
  488. initialize_main (&argc, &argv);
  489. set_program_name (argv[0]);
  490. setlocale (LC_ALL, "");
  491. bindtextdomain (PACKAGE, LOCALEDIR);
  492. textdomain (PACKAGE);
  493. atexit (close_stdout);
  494. separator = "\n";
  495. sentinel_length = 1;
  496. separator_ends_record = true;
  497. while ((optc = getopt_long (argc, argv, "brs:", longopts, NULL)) != -1)
  498. {
  499. switch (optc)
  500. {
  501. case 'b':
  502. separator_ends_record = false;
  503. break;
  504. case 'r':
  505. sentinel_length = 0;
  506. break;
  507. case 's':
  508. separator = optarg;
  509. if (*separator == 0)
  510. error (EXIT_FAILURE, 0, _("separator cannot be empty"));
  511. break;
  512. case_GETOPT_HELP_CHAR;
  513. case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
  514. default:
  515. usage (EXIT_FAILURE);
  516. }
  517. }
  518. if (sentinel_length == 0)
  519. {
  520. compiled_separator.buffer = NULL;
  521. compiled_separator.allocated = 0;
  522. compiled_separator.fastmap = compiled_separator_fastmap;
  523. compiled_separator.translate = NULL;
  524. error_message = re_compile_pattern (separator, strlen (separator),
  525. &compiled_separator);
  526. if (error_message)
  527. error (EXIT_FAILURE, 0, "%s", error_message);
  528. }
  529. else
  530. match_length = sentinel_length = strlen (separator);
  531. read_size = INITIAL_READSIZE;
  532. while (sentinel_length >= read_size / 2)
  533. {
  534. if (SIZE_MAX / 2 < read_size)
  535. xalloc_die ();
  536. read_size *= 2;
  537. }
  538. half_buffer_size = read_size + sentinel_length + 1;
  539. G_buffer_size = 2 * half_buffer_size;
  540. if (! (read_size < half_buffer_size && half_buffer_size < G_buffer_size))
  541. xalloc_die ();
  542. G_buffer = xmalloc (G_buffer_size);
  543. if (sentinel_length)
  544. {
  545. strcpy (G_buffer, separator);
  546. G_buffer += sentinel_length;
  547. }
  548. else
  549. {
  550. ++G_buffer;
  551. }
  552. file = (optind < argc
  553. ? (char const *const *) &argv[optind]
  554. : default_file_list);
  555. if (O_BINARY && ! isatty (STDOUT_FILENO))
  556. xfreopen (NULL, "wb", stdout);
  557. {
  558. size_t i;
  559. ok = true;
  560. for (i = 0; file[i]; ++i)
  561. ok &= tac_file (file[i]);
  562. }
  563. /* Flush the output buffer. */
  564. output ((char *) NULL, (char *) NULL);
  565. if (have_read_stdin && close (STDIN_FILENO) < 0)
  566. error (EXIT_FAILURE, errno, "-");
  567. exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);
  568. }