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