home *** CD-ROM | disk | FTP | other *** search
/ Fresh Fish 2 / FFMCD02.bin / useful / dist / gnu / fileutils / fileutils-3.9-amiga / src / dd.c < prev    next >
Encoding:
C/C++ Source or Header  |  1993-12-13  |  28.9 KB  |  1,112 lines

  1. /* dd -- convert a file while copying it.
  2.    Copyright (C) 1985, 1990, 1991 Free Software Foundation, Inc.
  3.  
  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.
  8.  
  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.
  13.  
  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., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  17.  
  18. /* Written by Paul Rubin, David MacKenzie, and Stuart Kemp. */
  19.  
  20. /* Options:
  21.  
  22.    Numbers can be followed by a multiplier:
  23.    b=512, c=1, k=1024, w=2, xm=number m
  24.  
  25.    if=FILE            Read from FILE instead of stdin.
  26.    of=FILE            Write to FILE instead of stdout; don't
  27.                 truncate FILE.
  28.    ibs=BYTES            Read BYTES bytes at a time.
  29.    obs=BYTES            Write BYTES bytes at a time.
  30.    bs=BYTES            Override ibs and obs.
  31.    cbs=BYTES            Convert BYTES bytes at a time.
  32.    skip=BLOCKS            Skip BLOCKS ibs-sized blocks at
  33.                 start of input.
  34.    seek=BLOCKS            Skip BLOCKS obs-sized blocks at
  35.                 start of output.
  36.    count=BLOCKS            Copy only BLOCKS input blocks.
  37.    conv=CONVERSION[,CONVERSION...]
  38.  
  39.    Conversions:
  40.    ascii            Convert EBCDIC to ASCII.
  41.    ebcdic            Convert ASCII to EBCDIC.
  42.    ibm                Convert ASCII to alternate EBCDIC.
  43.    block            Pad newline-terminated records to size of
  44.                 cbs, replacing newline with trailing spaces.
  45.    unblock            Replace trailing spaces in cbs-sized block
  46.                 with newline.
  47.    lcase            Change uppercase characters to lowercase.
  48.    ucase            Change lowercase characters to uppercase.
  49.    swab                Swap every pair of input bytes.
  50.                 Unlike the Unix dd, this works when an odd
  51.                 number of bytes are read.
  52.    noerror            Continue after read errors.
  53.    sync                Pad every input block to size of ibs with
  54.                 trailing NULs. */
  55.  
  56. #ifdef HAVE_CONFIG_H
  57. #if defined (CONFIG_BROKETS)
  58. /* We use <config.h> instead of "config.h" so that a compilation
  59.    using -I. -I$srcdir will use ./config.h rather than $srcdir/config.h
  60.    (which it would do because it found this file in $srcdir).  */
  61. #include <config.h>
  62. #else
  63. #include "config.h"
  64. #endif
  65. #endif
  66.  
  67. #include <stdio.h>
  68. #include <ctype.h>
  69.  
  70. #if !defined (isascii) || defined (STDC_HEADERS)
  71. #undef isascii
  72. #define isascii(c) 1
  73. #endif
  74.  
  75. #define ISLOWER(c) (isascii (c) && islower (c))
  76. #define ISUPPER(c) (isascii (c) && isupper (c))
  77. #define ISDIGIT(c) (isascii (c) && isdigit (c))
  78.  
  79. #include <sys/types.h>
  80. #include <signal.h>
  81. #include <getopt.h>
  82.  
  83. #include "system.h"
  84. #include "version.h"
  85.  
  86. #define equal(p, q) (strcmp ((p),(q)) == 0)
  87. #define max(a, b) ((a) > (b) ? (a) : (b))
  88. #define output_char(c) \
  89.   do { \
  90.   obuf[oc++] = (c); if (oc >= output_blocksize) write_output (); \
  91.   } while (0)
  92.  
  93. /* Default input and output blocksize. */
  94. #define DEFAULT_BLOCKSIZE 512
  95.  
  96. /* Conversions bit masks. */
  97. #define C_ASCII 01
  98. #define C_EBCDIC 02
  99. #define C_IBM 04
  100. #define C_BLOCK 010
  101. #define C_UNBLOCK 020
  102. #define C_LCASE 040
  103. #define C_UCASE 0100
  104. #define C_SWAB 0200
  105. #define C_NOERROR 0400
  106. #define C_NOTRUNC 01000
  107. #define C_SYNC 02000
  108. /* Use separate input and output buffers, and combine partial input blocks. */
  109. #define C_TWOBUFS 04000
  110.  
  111. char *xmalloc ();
  112. void error ();
  113.  
  114. static RETSIGTYPE interrupt_handler ();
  115. static int bit_count ();
  116. static int parse_integer ();
  117. static void apply_translations ();
  118. static void copy ();
  119. static void copy_simple ();
  120. static void copy_with_block ();
  121. static void copy_with_unblock ();
  122. static void parse_conversion ();
  123. static void print_stats ();
  124. static void translate_charset ();
  125. static void quit ();
  126. static void scanargs ();
  127. static void skip ();
  128. static void usage ();
  129. static void write_output ();
  130.  
  131. /* The name this program was run with. */
  132. char *program_name;
  133.  
  134. /* The name of the input file, or NULL for the standard input. */
  135. static char *input_file = NULL;
  136.  
  137. /* The input file descriptor. */
  138. static int input_fd = 0;
  139.  
  140. /* The name of the output file, or NULL for the standard output. */
  141. static char *output_file = NULL;
  142.  
  143. /* The output file descriptor. */
  144. static int output_fd = 1;
  145.  
  146. /* The number of bytes in which atomic reads are done. */
  147. static long input_blocksize = -1;
  148.  
  149. /* The number of bytes in which atomic writes are done. */
  150. static long output_blocksize = -1;
  151.  
  152. /* Conversion buffer size, in bytes.  0 prevents conversions. */
  153. static long conversion_blocksize = 0;
  154.  
  155. /* Skip this many records of `input_blocksize' bytes before input. */
  156. static long skip_records = 0;
  157.  
  158. /* Skip this many records of `output_blocksize' bytes before output. */
  159. static long seek_record = 0;
  160.  
  161. /* Copy only this many records.  <0 means no limit. */
  162. static int max_records = -1;
  163.  
  164. /* Bit vector of conversions to apply. */
  165. static int conversions_mask = 0;
  166.  
  167. /* If nonzero, filter characters through the translation table.  */
  168. static int translation_needed = 0;
  169.  
  170. /* Number of partial blocks written. */
  171. static unsigned w_partial = 0;
  172.  
  173. /* Number of full blocks written. */
  174. static unsigned w_full = 0;
  175.  
  176. /* Number of partial blocks read. */
  177. static unsigned r_partial = 0;
  178.  
  179. /* Number of full blocks read. */
  180. static unsigned r_full = 0;
  181.  
  182. /* Records truncated by conv=block. */
  183. static unsigned r_truncate = 0;
  184.  
  185. /* Output representation of newline and space characters.
  186.    They change if we're converting to EBCDIC.  */
  187. static unsigned char newline_character = '\n';
  188. static unsigned char space_character = ' ';
  189.  
  190. struct conversion
  191. {
  192.   char *convname;
  193.   int conversion;
  194. };
  195.  
  196. static struct conversion conversions[] =
  197. {
  198.   {"ascii", C_ASCII | C_TWOBUFS},    /* EBCDIC to ASCII. */
  199.   {"ebcdic", C_EBCDIC | C_TWOBUFS},    /* ASCII to EBCDIC. */
  200.   {"ibm", C_IBM | C_TWOBUFS},    /* Slightly different ASCII to EBCDIC. */
  201.   {"block", C_BLOCK | C_TWOBUFS},    /* Variable to fixed length records. */
  202.   {"unblock", C_UNBLOCK | C_TWOBUFS},    /* Fixed to variable length records. */
  203.   {"lcase", C_LCASE | C_TWOBUFS},    /* Translate upper to lower case. */
  204.   {"ucase", C_UCASE | C_TWOBUFS},    /* Translate lower to upper case. */
  205.   {"swab", C_SWAB | C_TWOBUFS},    /* Swap bytes of input. */
  206.   {"noerror", C_NOERROR},    /* Ignore i/o errors. */
  207.   {"notrunc", C_NOTRUNC},    /* Do not truncate output file. */
  208.   {"sync", C_SYNC},        /* Pad input records to ibs with NULs. */
  209.   {NULL, 0}
  210. };
  211.  
  212. /* Translation table formed by applying successive transformations. */
  213. static unsigned char trans_table[256];
  214.  
  215. static unsigned char const ascii_to_ebcdic[] =
  216. {
  217.   0, 01, 02, 03, 067, 055, 056, 057,
  218.   026, 05, 045, 013, 014, 015, 016, 017,
  219.   020, 021, 022, 023, 074, 075, 062, 046,
  220.   030, 031, 077, 047, 034, 035, 036, 037,
  221.   0100, 0117, 0177, 0173, 0133, 0154, 0120, 0175,
  222.   0115, 0135, 0134, 0116, 0153, 0140, 0113, 0141,
  223.   0360, 0361, 0362, 0363, 0364, 0365, 0366, 0367,
  224.   0370, 0371, 0172, 0136, 0114, 0176, 0156, 0157,
  225.   0174, 0301, 0302, 0303, 0304, 0305, 0306, 0307,
  226.   0310, 0311, 0321, 0322, 0323, 0324, 0325, 0326,
  227.   0327, 0330, 0331, 0342, 0343, 0344, 0345, 0346,
  228.   0347, 0350, 0351, 0112, 0340, 0132, 0137, 0155,
  229.   0171, 0201, 0202, 0203, 0204, 0205, 0206, 0207,
  230.   0210, 0211, 0221, 0222, 0223, 0224, 0225, 0226,
  231.   0227, 0230, 0231, 0242, 0243, 0244, 0245, 0246,
  232.   0247, 0250, 0251, 0300, 0152, 0320, 0241, 07,
  233.   040, 041, 042, 043, 044, 025, 06, 027,
  234.   050, 051, 052, 053, 054, 011, 012, 033,
  235.   060, 061, 032, 063, 064, 065, 066, 010,
  236.   070, 071, 072, 073, 04, 024, 076, 0341,
  237.   0101, 0102, 0103, 0104, 0105, 0106, 0107, 0110,
  238.   0111, 0121, 0122, 0123, 0124, 0125, 0126, 0127,
  239.   0130, 0131, 0142, 0143, 0144, 0145, 0146, 0147,
  240.   0150, 0151, 0160, 0161, 0162, 0163, 0164, 0165,
  241.   0166, 0167, 0170, 0200, 0212, 0213, 0214, 0215,
  242.   0216, 0217, 0220, 0232, 0233, 0234, 0235, 0236,
  243.   0237, 0240, 0252, 0253, 0254, 0255, 0256, 0257,
  244.   0260, 0261, 0262, 0263, 0264, 0265, 0266, 0267,
  245.   0270, 0271, 0272, 0273, 0274, 0275, 0276, 0277,
  246.   0312, 0313, 0314, 0315, 0316, 0317, 0332, 0333,
  247.   0334, 0335, 0336, 0337, 0352, 0353, 0354, 0355,
  248.   0356, 0357, 0372, 0373, 0374, 0375, 0376, 0377
  249. };
  250.  
  251. static unsigned char const ascii_to_ibm[] =
  252. {
  253.   0, 01, 02, 03, 067, 055, 056, 057,
  254.   026, 05, 045, 013, 014, 015, 016, 017,
  255.   020, 021, 022, 023, 074, 075, 062, 046,
  256.   030, 031, 077, 047, 034, 035, 036, 037,
  257.   0100, 0132, 0177, 0173, 0133, 0154, 0120, 0175,
  258.   0115, 0135, 0134, 0116, 0153, 0140, 0113, 0141,
  259.   0360, 0361, 0362, 0363, 0364, 0365, 0366, 0367,
  260.   0370, 0371, 0172, 0136, 0114, 0176, 0156, 0157,
  261.   0174, 0301, 0302, 0303, 0304, 0305, 0306, 0307,
  262.   0310, 0311, 0321, 0322, 0323, 0324, 0325, 0326,
  263.   0327, 0330, 0331, 0342, 0343, 0344, 0345, 0346,
  264.   0347, 0350, 0351, 0255, 0340, 0275, 0137, 0155,
  265.   0171, 0201, 0202, 0203, 0204, 0205, 0206, 0207,
  266.   0210, 0211, 0221, 0222, 0223, 0224, 0225, 0226,
  267.   0227, 0230, 0231, 0242, 0243, 0244, 0245, 0246,
  268.   0247, 0250, 0251, 0300, 0117, 0320, 0241, 07,
  269.   040, 041, 042, 043, 044, 025, 06, 027,
  270.   050, 051, 052, 053, 054, 011, 012, 033,
  271.   060, 061, 032, 063, 064, 065, 066, 010,
  272.   070, 071, 072, 073, 04, 024, 076, 0341,
  273.   0101, 0102, 0103, 0104, 0105, 0106, 0107, 0110,
  274.   0111, 0121, 0122, 0123, 0124, 0125, 0126, 0127,
  275.   0130, 0131, 0142, 0143, 0144, 0145, 0146, 0147,
  276.   0150, 0151, 0160, 0161, 0162, 0163, 0164, 0165,
  277.   0166, 0167, 0170, 0200, 0212, 0213, 0214, 0215,
  278.   0216, 0217, 0220, 0232, 0233, 0234, 0235, 0236,
  279.   0237, 0240, 0252, 0253, 0254, 0255, 0256, 0257,
  280.   0260, 0261, 0262, 0263, 0264, 0265, 0266, 0267,
  281.   0270, 0271, 0272, 0273, 0274, 0275, 0276, 0277,
  282.   0312, 0313, 0314, 0315, 0316, 0317, 0332, 0333,
  283.   0334, 0335, 0336, 0337, 0352, 0353, 0354, 0355,
  284.   0356, 0357, 0372, 0373, 0374, 0375, 0376, 0377
  285. };
  286.  
  287. static unsigned char const ebcdic_to_ascii[] =
  288. {
  289.   0, 01, 02, 03, 0234, 011, 0206, 0177,
  290.   0227, 0215, 0216, 013, 014, 015, 016, 017,
  291.   020, 021, 022, 023, 0235, 0205, 010, 0207,
  292.   030, 031, 0222, 0217, 034, 035, 036, 037,
  293.   0200, 0201, 0202, 0203, 0204, 012, 027, 033,
  294.   0210, 0211, 0212, 0213, 0214, 05, 06, 07,
  295.   0220, 0221, 026, 0223, 0224, 0225, 0226, 04,
  296.   0230, 0231, 0232, 0233, 024, 025, 0236, 032,
  297.   040, 0240, 0241, 0242, 0243, 0244, 0245, 0246,
  298.   0247, 0250, 0133, 056, 074, 050, 053, 041,
  299.   046, 0251, 0252, 0253, 0254, 0255, 0256, 0257,
  300.   0260, 0261, 0135, 044, 052, 051, 073, 0136,
  301.   055, 057, 0262, 0263, 0264, 0265, 0266, 0267,
  302.   0270, 0271, 0174, 054, 045, 0137, 076, 077,
  303.   0272, 0273, 0274, 0275, 0276, 0277, 0300, 0301,
  304.   0302, 0140, 072, 043, 0100, 047, 075, 042,
  305.   0303, 0141, 0142, 0143, 0144, 0145, 0146, 0147,
  306.   0150, 0151, 0304, 0305, 0306, 0307, 0310, 0311,
  307.   0312, 0152, 0153, 0154, 0155, 0156, 0157, 0160,
  308.   0161, 0162, 0313, 0314, 0315, 0316, 0317, 0320,
  309.   0321, 0176, 0163, 0164, 0165, 0166, 0167, 0170,
  310.   0171, 0172, 0322, 0323, 0324, 0325, 0326, 0327,
  311.   0330, 0331, 0332, 0333, 0334, 0335, 0336, 0337,
  312.   0340, 0341, 0342, 0343, 0344, 0345, 0346, 0347,
  313.   0173, 0101, 0102, 0103, 0104, 0105, 0106, 0107,
  314.   0110, 0111, 0350, 0351, 0352, 0353, 0354, 0355,
  315.   0175, 0112, 0113, 0114, 0115, 0116, 0117, 0120,
  316.   0121, 0122, 0356, 0357, 0360, 0361, 0362, 0363,
  317.   0134, 0237, 0123, 0124, 0125, 0126, 0127, 0130,
  318.   0131, 0132, 0364, 0365, 0366, 0367, 0370, 0371,
  319.   060, 061, 062, 063, 064, 065, 066, 067,
  320.   070, 071, 0372, 0373, 0374, 0375, 0376, 0377
  321. };
  322.  
  323. /* If non-zero, display usage information and exit.  */
  324. static int show_help;
  325.  
  326. /* If non-zero, print the version on standard output and exit.  */
  327. static int show_version;
  328.  
  329. static struct option const long_options[] =
  330. {
  331.   {"help", no_argument, &show_help, 1},
  332.   {"version", no_argument, &show_version, 1},
  333.   {0, 0, 0, 0}
  334. };
  335.  
  336. main (argc, argv)
  337.      int argc;
  338.      char **argv;
  339. {
  340. #ifdef _POSIX_VERSION
  341.   struct sigaction sigact;
  342. #endif /* _POSIX_VERSION */
  343.   int i;
  344.  
  345.   program_name = argv[0];
  346.  
  347.   /* Initialize translation table to identity translation. */
  348.   for (i = 0; i < 256; i++)
  349.     trans_table[i] = i;
  350.  
  351.   /* Decode arguments. */
  352.   scanargs (argc, argv);
  353.  
  354.   if (show_version)
  355.     {
  356.       printf ("%s\n", version_string);
  357.       exit (0);
  358.     }
  359.  
  360.   if (show_help)
  361.     usage (0);
  362.  
  363.   apply_translations ();
  364.  
  365.   if (input_file != NULL)
  366.     {
  367.       input_fd = open (input_file, O_RDONLY);
  368.       if (input_fd < 0)
  369.     error (1, errno, "%s", input_file);
  370.     }
  371.   else
  372.     input_file = "standard input";
  373.  
  374.   if (input_fd == output_fd)
  375.     error (1, 0, "standard %s is closed", input_fd == 0 ? "input" : "output");
  376.  
  377.   if (output_file != NULL)
  378.     {
  379.       int omode = O_RDWR | O_CREAT;
  380.  
  381.       if (seek_record == 0 && !(conversions_mask & C_NOTRUNC))
  382.     omode |= O_TRUNC;
  383.       output_fd = open (output_file, omode, 0666);
  384.       if (output_fd < 0)
  385.     error (1, errno, "%s", output_file);
  386. #ifdef HAVE_FTRUNCATE
  387.       if (seek_record > 0 && !(conversions_mask & C_NOTRUNC))
  388.     {
  389.       if (ftruncate (output_fd, seek_record * output_blocksize) < 0)
  390.         error (0, errno, "%s", output_file);
  391.     }
  392. #endif
  393.     }
  394.   else
  395.     output_file = "standard output";
  396.  
  397. #ifdef _POSIX_VERSION
  398.   sigaction (SIGINT, NULL, &sigact);
  399.   if (sigact.sa_handler != SIG_IGN)
  400.     {
  401.       sigact.sa_handler = interrupt_handler;
  402.       sigemptyset (&sigact.sa_mask);
  403.       sigact.sa_flags = 0;
  404.       sigaction (SIGINT, &sigact, NULL);
  405.     }
  406. #else                /* !_POSIX_VERSION */
  407.   if (signal (SIGINT, SIG_IGN) != SIG_IGN)
  408.     signal (SIGINT, interrupt_handler);
  409. #endif                /* !_POSIX_VERSION */
  410.   copy ();
  411. }
  412.  
  413. /* Throw away RECORDS blocks of BLOCKSIZE bytes on file descriptor FDESC,
  414.    which is open with read permission for FILE.  Store up to BLOCKSIZE
  415.    bytes of the data at a time in BUF, if necessary. */
  416.  
  417. static void
  418. skip (fdesc, file, records, blocksize, buf)
  419.      int fdesc;
  420.      char *file;
  421.      long records;
  422.      long blocksize;
  423.      char *buf;
  424. {
  425.   struct stat stats;
  426.  
  427.   /* Use fstat instead of checking for errno == ESPIPE because
  428.      lseek doesn't work on some special files but doesn't return an
  429.      error, either. */
  430.   if (fstat (fdesc, &stats))
  431.     {
  432.       error (0, errno, "%s", file);
  433.       quit (1);
  434.     }
  435.  
  436.   if (S_ISREG (stats.st_mode))
  437.     {
  438.       if (lseek (fdesc, records * blocksize, SEEK_SET) < 0)
  439.     {
  440.       error (0, errno, "%s", file);
  441.       quit (1);
  442.     }
  443.     }
  444.   else
  445.     {
  446.       while (records-- > 0)
  447.     {
  448.       if (read (fdesc, buf, blocksize) < 0)
  449.         {
  450.           error (0, errno, "%s", file);
  451.           quit (1);
  452.         }
  453.       /* FIXME If fewer bytes were read than requested, meaning that
  454.          EOF was reached, POSIX wants the output file padded with NULs. */
  455.     }
  456.     }
  457. }
  458.  
  459. /* Apply the character-set translations specified by the user
  460.    to the NREAD bytes in BUF.  */
  461.  
  462. static void
  463. translate_buffer (buf, nread)
  464.      unsigned char *buf;
  465.      int nread;
  466. {
  467.   register unsigned char *cp;
  468.   register int i;
  469.  
  470.   for (i = nread, cp = buf; i; i--, cp++)
  471.     *cp = trans_table[*cp];
  472. }
  473.  
  474. /* If nonnzero, the last char from the previous call to `swab_buffer'
  475.    is saved in `saved_char'.  */
  476. static int char_is_saved = 0;
  477.  
  478. /* Odd char from previous call.  */
  479. static unsigned char saved_char;
  480.  
  481. /* Swap NREAD bytes in BUF, plus possibly an initial char from the
  482.    previous call.  If NREAD is odd, save the last char for the
  483.    next call.   Return the new start of the BUF buffer.  */
  484.  
  485. static unsigned char *
  486. swab_buffer (buf, nread)
  487.      unsigned char *buf;
  488.      int *nread;
  489. {
  490.   unsigned char *bufstart = buf;
  491.   register unsigned char *cp;
  492.   register int i;
  493.  
  494.   /* Is a char left from last time?  */
  495.   if (char_is_saved)
  496.     {
  497.       *--bufstart = saved_char;
  498.       (*nread)++;
  499.       char_is_saved = 0;
  500.     }
  501.  
  502.   if (*nread & 1)
  503.     {
  504.       /* An odd number of chars are in the buffer.  */
  505.       saved_char = bufstart[--*nread];
  506.       char_is_saved = 1;
  507.     }
  508.  
  509.   /* Do the byte-swapping by moving every second character two
  510.      positions toward the end, working from the end of the buffer
  511.      toward the beginning.  This way we only move half of the data.  */
  512.  
  513.   cp = bufstart + *nread;    /* Start one char past the last.  */
  514.   for (i = *nread / 2; i; i--, cp -= 2)
  515.     *cp = *(cp - 2);
  516.  
  517.   return ++bufstart;
  518. }
  519.  
  520. /* Output buffer. */
  521. static unsigned char *obuf;
  522.  
  523. /* Current index into `obuf'. */
  524. static int oc = 0;
  525.  
  526. /* Index into current line, for `conv=block' and `conv=unblock'.  */
  527. static int col = 0;
  528.  
  529. /* The main loop.  */
  530.  
  531. static void
  532. copy ()
  533. {
  534.   unsigned char *ibuf, *bufstart; /* Input buffer. */
  535.   int nread;            /* Bytes read in the current block. */
  536.   int exit_status = 0;
  537.  
  538.   /* Leave an extra byte at the beginning and end of `ibuf' for conv=swab.  */
  539.   ibuf = (unsigned char *) xmalloc (input_blocksize + 2) + 1;
  540.   if (conversions_mask & C_TWOBUFS)
  541.     obuf = (unsigned char *) xmalloc (output_blocksize);
  542.   else
  543.     obuf = ibuf;
  544.  
  545.   if (skip_records > 0)
  546.     skip (input_fd, input_file, skip_records, input_blocksize, ibuf);
  547.  
  548.   if (seek_record > 0)
  549.     skip (output_fd, output_file, seek_record, output_blocksize, obuf);
  550.  
  551.   if (max_records == 0)
  552.     quit (exit_status);
  553.  
  554.   while (1)
  555.     {
  556.       if (max_records >= 0 && r_partial + r_full >= max_records)
  557.     break;
  558.  
  559.       /* Zero the buffer before reading, so that if we get a read error,
  560.      whatever data we are able to read is followed by zeros.
  561.      This minimizes data loss. */
  562.       if ((conversions_mask & C_SYNC) && (conversions_mask & C_NOERROR))
  563.     bzero (ibuf, input_blocksize);
  564.  
  565.       nread = read (input_fd, ibuf, input_blocksize);
  566.  
  567.       if (nread == 0)
  568.     break;            /* EOF.  */
  569.  
  570.       if (nread < 0)
  571.     {
  572.       error (0, errno, "%s", input_file);
  573.       if (conversions_mask & C_NOERROR)
  574.         {
  575.           print_stats ();
  576.           /* Seek past the bad block if possible. */
  577.           lseek (input_fd, input_blocksize, SEEK_CUR);
  578.           if (conversions_mask & C_SYNC)
  579.         /* Replace the missing input with null bytes and
  580.            proceed normally.  */
  581.         nread = 0;
  582.           else
  583.         continue;
  584.         }
  585.       else
  586.         {
  587.           /* Write any partial block. */
  588.           exit_status = 2;
  589.           break;
  590.         }
  591.     }
  592.  
  593.       if (nread < input_blocksize)
  594.     {
  595.       r_partial++;
  596.       if (conversions_mask & C_SYNC)
  597.         {
  598.           if (!(conversions_mask & C_NOERROR))
  599.         /* If C_NOERROR, we zeroed the block before reading. */
  600.         bzero (ibuf + nread, input_blocksize - nread);
  601.           nread = input_blocksize;
  602.         }
  603.     }
  604.       else
  605.     r_full++;
  606.  
  607.       if (ibuf == obuf)        /* If not C_TWOBUFS. */
  608.     {
  609.       int nwritten = write (output_fd, obuf, nread);
  610.       if (nwritten != nread)
  611.         {
  612.           error (0, errno, "%s", output_file);
  613.           if (nwritten > 0)
  614.         w_partial++;
  615.           quit (1);
  616.         }
  617.       else if (nread == input_blocksize)
  618.         w_full++;
  619.       else
  620.         w_partial++;
  621.       continue;
  622.     }
  623.  
  624.       /* Do any translations on the whole buffer at once.  */
  625.  
  626.       if (translation_needed)
  627.     translate_buffer (ibuf, nread);
  628.  
  629.       if (conversions_mask & C_SWAB)
  630.     bufstart = swab_buffer (ibuf, &nread);
  631.       else
  632.     bufstart = ibuf;
  633.  
  634.       if (conversions_mask & C_BLOCK)
  635.         copy_with_block (bufstart, nread);
  636.       else if (conversions_mask & C_UNBLOCK)
  637.     copy_with_unblock (bufstart, nread);
  638.       else
  639.     copy_simple (bufstart, nread);
  640.     }
  641.  
  642.   /* If we have a char left as a result of conv=swab, output it.  */
  643.   if (char_is_saved)
  644.     {
  645.       if (conversions_mask & C_BLOCK)
  646.         copy_with_block (&saved_char, 1);
  647.       else if (conversions_mask & C_UNBLOCK)
  648.     copy_with_unblock (&saved_char, 1);
  649.       else
  650.     output_char (saved_char);
  651.     }
  652.  
  653.   if ((conversions_mask & C_BLOCK) && col > 0)
  654.     {
  655.       /* If the final input line didn't end with a '\n', pad
  656.      the output block to `conversion_blocksize' chars.  */
  657.       int pending_spaces = max (0, conversion_blocksize - col);
  658.       while (pending_spaces)
  659.     {
  660.       output_char (space_character);
  661.       --pending_spaces;
  662.     }
  663.     }
  664.  
  665.   if ((conversions_mask & C_UNBLOCK) && col == conversion_blocksize)
  666.     /* Add a final '\n' if there are exactly `conversion_blocksize'
  667.        characters in the final record. */
  668.     output_char (newline_character);
  669.  
  670.   /* Write out the last block. */
  671.   if (oc > 0)
  672.     {
  673.       int nwritten = write (output_fd, obuf, oc);
  674.       if (nwritten > 0)
  675.     w_partial++;
  676.       if (nwritten != oc)
  677.     {
  678.       error (0, errno, "%s", output_file);
  679.       quit (1);
  680.     }
  681.     }
  682.  
  683.   free (ibuf - 1);
  684.   if (obuf != ibuf)
  685.     free (obuf);
  686.  
  687.   quit (exit_status);
  688. }
  689.  
  690. /* Copy NREAD bytes of BUF, with no conversions.  */
  691.  
  692. static void
  693. copy_simple (buf, nread)
  694.      unsigned char *buf;
  695.      int nread;
  696. {
  697.   int nfree;            /* Number of unused bytes in `obuf'.  */
  698.   unsigned char *start = buf; /* First uncopied char in BUF.  */
  699.  
  700.   do
  701.     {
  702.       nfree = output_blocksize - oc;
  703.       if (nfree > nread)
  704.     nfree = nread;
  705.  
  706.       bcopy (start, obuf + oc, nfree);
  707.  
  708.       nread -= nfree;        /* Update the number of bytes left to copy. */
  709.       start += nfree;
  710.       oc += nfree;
  711.       if (oc >= output_blocksize)
  712.     write_output ();
  713.     }
  714.   while (nread > 0);
  715. }
  716.  
  717. /* Copy NREAD bytes of BUF, doing conv=block
  718.    (pad newline-terminated records to `conversion_blocksize',
  719.    replacing the newline with trailing spaces).  */
  720.  
  721. static void
  722. copy_with_block (buf, nread)
  723.      unsigned char *buf;
  724.      int nread;
  725. {
  726.   register int i;
  727.  
  728.   for (i = nread; i; i--, buf++)
  729.     {
  730.       if (*buf == newline_character)
  731.     {
  732.       int pending_spaces = max (0, conversion_blocksize - col);
  733.       while (pending_spaces)
  734.         {
  735.           output_char (space_character);
  736.           --pending_spaces;
  737.         }
  738.       col = 0;
  739.     }
  740.       else
  741.     {
  742.       if (col == conversion_blocksize)
  743.         r_truncate++;
  744.       else if (col < conversion_blocksize)
  745.         output_char (*buf);
  746.       col++;
  747.     }
  748.     }
  749. }
  750.  
  751. /* Copy NREAD bytes of BUF, doing conv=unblock
  752.    (replace trailing spaces in `conversion_blocksize'-sized records
  753.    with a newline).  */
  754.  
  755. static void
  756. copy_with_unblock (buf, nread)
  757.      unsigned char *buf;
  758.      int nread;
  759. {
  760.   register int i;
  761.   register unsigned char c;
  762.   static int pending_spaces = 0;
  763.  
  764.   for (i = 0; i < nread; i++)
  765.     {
  766.       c = buf[i];
  767.  
  768.       if (col++ >= conversion_blocksize)
  769.     {
  770.       col = pending_spaces = 0; /* Wipe out any pending spaces.  */
  771.       i--;            /* Push the char back; get it later. */
  772.       output_char (newline_character);
  773.     }
  774.       else if (c == space_character)
  775.     pending_spaces++;
  776.       else
  777.     {
  778.       /* `c' is the character after a run of spaces that were not
  779.          at the end of the conversion buffer.  Output them.  */
  780.       while (pending_spaces)
  781.         {
  782.           output_char (space_character);
  783.           --pending_spaces;
  784.         }
  785.       output_char (c);
  786.     }
  787.     }
  788. }
  789.  
  790. /* Write, then empty, the output buffer `obuf'. */
  791.  
  792. static void
  793. write_output ()
  794. {
  795.   int nwritten = write (output_fd, obuf, output_blocksize);
  796.   if (nwritten != output_blocksize)
  797.     {
  798.       error (0, errno, "%s", output_file);
  799.       if (nwritten > 0)
  800.     w_partial++;
  801.       quit (1);
  802.     }
  803.   else
  804.     w_full++;
  805.   oc = 0;
  806. }
  807.  
  808. static void
  809. scanargs (argc, argv)
  810.      int argc;
  811.      char **argv;
  812. {
  813.   int i, n;
  814.   int c;
  815.  
  816.   while ((c = getopt_long (argc, argv, "", long_options, (int *) 0)) != EOF)
  817.     {
  818.       switch (c)
  819.     {
  820.     case 0:
  821.       break;
  822.  
  823.     default:
  824.       usage (1);
  825.     }
  826.     }
  827.  
  828.   for (i = optind; i < argc; i++)
  829.     {
  830.       char *name, *val;
  831.  
  832.       name = argv[i];
  833.       val = index (name, '=');
  834.       if (val == NULL)
  835.     {
  836.       error (0, 0, "unrecognized option `%s'", name);
  837.       usage (1);
  838.     }
  839.       *val++ = '\0';
  840.  
  841.       if (equal (name, "if"))
  842.     input_file = val;
  843.       else if (equal (name, "of"))
  844.     output_file = val;
  845.       else if (equal (name, "conv"))
  846.     parse_conversion (val);
  847.       else
  848.     {
  849.       n = parse_integer (val);
  850.       if (n < 0)
  851.         error (1, 0, "invalid number `%s'", val);
  852.  
  853.       if (equal (name, "ibs"))
  854.         {
  855.           input_blocksize = n;
  856.           conversions_mask |= C_TWOBUFS;
  857.         }
  858.       else if (equal (name, "obs"))
  859.         {
  860.           output_blocksize = n;
  861.           conversions_mask |= C_TWOBUFS;
  862.         }
  863.       else if (equal (name, "bs"))
  864.         output_blocksize = input_blocksize = n;
  865.       else if (equal (name, "cbs"))
  866.         conversion_blocksize = n;
  867.       else if (equal (name, "skip"))
  868.         skip_records = n;
  869.       else if (equal (name, "seek"))
  870.         seek_record = n;
  871.       else if (equal (name, "count"))
  872.         max_records = n;
  873.       else
  874.         {
  875.           error (0, 0, "unrecognized option `%s=%s'", name, val);
  876.           usage (1);
  877.         }
  878.     }
  879.     }
  880.  
  881.   /* If bs= was given, both `input_blocksize' and `output_blocksize' will
  882.      have been set to non-negative values.  If either has not been set,
  883.      bs= was not given, so make sure two buffers are used. */
  884.   if (input_blocksize == -1 || output_blocksize == -1)
  885.     conversions_mask |= C_TWOBUFS;
  886.   if (input_blocksize == -1)
  887.     input_blocksize = DEFAULT_BLOCKSIZE;
  888.   if (output_blocksize == -1)
  889.     output_blocksize = DEFAULT_BLOCKSIZE;
  890.   if (conversion_blocksize == 0)
  891.     conversions_mask &= ~(C_BLOCK | C_UNBLOCK);
  892. }
  893.  
  894. /* Return the value of STR, interpreted as a non-negative decimal integer,
  895.    optionally multiplied by various values.
  896.    Return -1 if STR does not represent a number in this format. */
  897.  
  898. static int
  899. parse_integer (str)
  900.      char *str;
  901. {
  902.   register int n = 0;
  903.   register int temp;
  904.   register char *p = str;
  905.  
  906.   while (ISDIGIT (*p))
  907.     {
  908.       n = n * 10 + *p - '0';
  909.       p++;
  910.     }
  911. loop:
  912.   switch (*p++)
  913.     {
  914.     case '\0':
  915.       return n;
  916.     case 'b':
  917.       n *= 512;
  918.       goto loop;
  919.     case 'c':
  920.       goto loop;
  921.     case 'k':
  922.       n *= 1024;
  923.       goto loop;
  924.     case 'w':
  925.       n *= 2;
  926.       goto loop;
  927.     case 'x':
  928.       temp = parse_integer (p);
  929.       if (temp == -1)
  930.     return -1;
  931.       n *= temp;
  932.       break;
  933.     default:
  934.       return -1;
  935.     }
  936.   return n;
  937. }
  938.  
  939. /* Interpret one "conv=..." option. */
  940.  
  941. static void
  942. parse_conversion (str)
  943.      char *str;
  944. {
  945.   char *new;
  946.   int i;
  947.  
  948.   do
  949.     {
  950.       new = index (str, ',');
  951.       if (new != NULL)
  952.     *new++ = '\0';
  953.       for (i = 0; conversions[i].convname != NULL; i++)
  954.     if (equal (conversions[i].convname, str))
  955.       {
  956.         conversions_mask |= conversions[i].conversion;
  957.         break;
  958.       }
  959.       if (conversions[i].convname == NULL)
  960.     {
  961.       error (0, 0, "%s: invalid conversion", str);
  962.       usage (1);
  963.     }
  964.       str = new;
  965.   } while (new != NULL);
  966. }
  967.  
  968. /* Fix up translation table. */
  969.  
  970. static void
  971. apply_translations ()
  972. {
  973.   int i;
  974.  
  975. #define MX(a) (bit_count (conversions_mask & (a)))
  976.   if ((MX (C_ASCII | C_EBCDIC | C_IBM) > 1)
  977.       || (MX (C_BLOCK | C_UNBLOCK) > 1)
  978.       || (MX (C_LCASE | C_UCASE) > 1)
  979.       || (MX (C_UNBLOCK | C_SYNC) > 1))
  980.     {
  981.       error (1, 0, "\
  982. only one conv in {ascii,ebcdic,ibm}, {lcase,ucase}, {block,unblock}, {unblock,sync}");
  983.     }
  984. #undef MX
  985.  
  986.   if (conversions_mask & C_ASCII)
  987.     translate_charset (ebcdic_to_ascii);
  988.  
  989.   if (conversions_mask & C_UCASE)
  990.     {
  991.       for (i = 0; i < 256; i++)
  992.     if (ISLOWER (trans_table[i]))
  993.       trans_table[i] = toupper (trans_table[i]);
  994.       translation_needed = 1;
  995.     }
  996.   else if (conversions_mask & C_LCASE)
  997.     {
  998.       for (i = 0; i < 256; i++)
  999.     if (ISUPPER (trans_table[i]))
  1000.       trans_table[i] = tolower (trans_table[i]);
  1001.       translation_needed = 1;
  1002.     }
  1003.  
  1004.   if (conversions_mask & C_EBCDIC)
  1005.     {
  1006.       translate_charset (ascii_to_ebcdic);
  1007.       newline_character = ascii_to_ebcdic['\n'];
  1008.       space_character = ascii_to_ebcdic[' '];
  1009.     }
  1010.   else if (conversions_mask & C_IBM)
  1011.     {
  1012.       translate_charset (ascii_to_ibm);
  1013.       newline_character = ascii_to_ibm['\n'];
  1014.       space_character = ascii_to_ibm[' '];
  1015.     }
  1016. }
  1017.  
  1018. static void
  1019. translate_charset (new_trans)
  1020.      unsigned char *new_trans;
  1021. {
  1022.   int i;
  1023.  
  1024.   for (i = 0; i < 256; i++)
  1025.     trans_table[i] = new_trans[trans_table[i]];
  1026.   translation_needed = 1;
  1027. }
  1028.  
  1029. /* Return the number of 1 bits in `i'. */
  1030.  
  1031. static int
  1032. bit_count (i)
  1033.      register unsigned int i;
  1034. {
  1035.   register int set_bits;
  1036.  
  1037.   for (set_bits = 0; i != 0; set_bits++)
  1038.     i &= i - 1;
  1039.   return set_bits;
  1040. }
  1041.  
  1042. static void
  1043. print_stats ()
  1044. {
  1045.   fprintf (stderr, "%u+%u records in\n", r_full, r_partial);
  1046.   fprintf (stderr, "%u+%u records out\n", w_full, w_partial);
  1047.   if (r_truncate > 0)
  1048.     fprintf (stderr, "%u truncated record%s\n", r_truncate,
  1049.          r_truncate == 1 ? "" : "s");
  1050. }
  1051.  
  1052. static void
  1053. quit (code)
  1054.      int code;
  1055. {
  1056.   int errcode = code ? code : 1;
  1057.   print_stats ();
  1058.   if (close (input_fd) < 0)
  1059.     error (errcode, errno, "%s", input_file);
  1060.   if (close (output_fd) < 0)
  1061.     error (errcode, errno, "%s", output_file);
  1062.   exit (code);
  1063. }
  1064.  
  1065. static RETSIGTYPE
  1066. interrupt_handler ()
  1067. {
  1068.   quit (1);
  1069. }
  1070.  
  1071. static void
  1072. usage (status)
  1073.      int status;
  1074. {
  1075.   if (status != 0)
  1076.     fprintf (stderr, "Try `%s --help' for more information.\n",
  1077.          program_name);
  1078.   else
  1079.     {
  1080.       printf ("Usage: %s [OPTION]...\n", program_name);
  1081.       printf ("\
  1082. \n\
  1083.   bs=BYTES        force ibs=BYTES and obs=BYTES\n\
  1084.   cbs=BYTES       convert BYTES bytes at a time\n\
  1085.   conv=KEYWORDS   convert the file as per the comma separated keyword list\n\
  1086.   count=BLOCKS    copy only BLOCKS input blocks\n\
  1087.   ibs=BYTES       read BYTES bytes at a time\n\
  1088.   if=FILE         read from FILE instead of stdin\n\
  1089.   obs=BYTES       write BYTES bytes at a time\n\
  1090.   of=FILE         write to FILE instead of stdout, don't truncate file\n\
  1091.   seek=BLOCKS     skip BLOCKS obs-sized blocks at start of output\n\
  1092.   skip=BLOCKS     skip BLOCKS ibs-sized blocks at start of input\n\
  1093.       --help      display this help and exit\n\
  1094.       --version   output version information and exit\n\
  1095. \n\
  1096. BYTES may be suffixed: by xM for multiplication by M, by c for x1,\n\
  1097. by w for x2, by b for x512, by k for x1024.  Each KEYWORD may be:\n\
  1098. \n\
  1099.   ascii     from EBCDIC to ASCII\n\
  1100.   ebcdic    from ASCII to EBCDIC\n\
  1101.   ibm       from ASCII to alternated EBCDIC\n\
  1102.   block     pad newline-terminated records with spaces to cbs-size \n\
  1103.   unblock   replace trailing spaces in cbs-size records with newline\n\
  1104.   lcase     change uppercase to lowercase\n\
  1105.   ucase     change lowercase to uppercase\n\
  1106.   swab      swap every pair of input bytes\n\
  1107.   noerror   continue after read errors\n\
  1108.   sync      pad every input block with NULs to ibs-size\n");
  1109.     }
  1110.   exit (status);
  1111. }
  1112.