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