INSERT.c (new Jan688 release: reads stdin & better error messages)

Bob Webber webber at athos.rutgers.edu
Mon Jan 9 08:59:38 AEST 1989



/* 
   This program writes contents of file descriptor fdin onto the contents
   of file descriptor fdout and then adjusts the size of fdout to be the
   size of fdin.  If it is passed two parameters, the first is the file
   name for fdin and the second is the file name for fdout.  If it is
   passed one parameter, then fdin is standard input and the one parameter
   is the file name for fdout.

   Note: code uses BSD/SunOS functions ftruncate.  This is crucial to
         its usefulness.  If someone knows a POSIX/V7 equiv, I would
         be interested in hearing of it. [Am posting question to 
         comp.unix.wizards, so any discussion would be best there.]


*/


#include <stdio.h>
#include <errno.h>
#include <fcntl.h> 
#include <sys/types.h>
#include <sys/file.h>
#include <sys/param.h>

extern long lseek();

main(argc,argv)
     int argc;
     char *argv[];
{
  int fdin, fdout;
  int ReadExit;
  int ReadSize;
  
  char chs[MAXBSIZE];

  if (argc == 3) {
    if ((fdin = open(argv[1],O_RDONLY)) == -1) {
      perror("Error 1 : ((fdin = open(argv[1],O_RDONLY)) == -1):");
      exit(1);
    }
    if (lseek(fdin,(long) 0,L_SET) != 0) {
      perror("Error 2 :(lseek(fdin,(long) 0,L_SET) != 0): ");
      exit(2);
    }
    if ((fdout = open(argv[2],O_WRONLY)) == -1) {
      perror("Error 3 : ((fdout = open(argv[2],O_WRONLY)) == -1):");
      exit(3);
    }
    if (lseek(fdout,(long) 0,L_SET) != 0) {
      perror("Error 4 : (lseek(fdout,(long) 0,L_SET) != 0) :");
      exit(4);
    }
  } else if (argc == 2) {
    fdin = 0;
    if ((fdout = open(argv[1],O_WRONLY)) == -1) {
      perror("Error 5 :((fdout = open(argv[1],O_WRONLY)) == -1) :");
      exit(5);
    }
    if (lseek(fdout,(long) 0,L_SET) != 0) {
      perror("Error 6 : (lseek(fdout,(long) 0,L_SET) != 0) :");
      exit(6);
    }
  } else {
    (void)fprintf(stderr,"Error 7 [%d]: Read the source before using\n",argc);
    exit(7);
  }
  ReadSize = 0;
  while ((ReadExit = read(fdin,chs,MAXBSIZE)) >0) {
    ReadSize += ReadExit;
    if (write(fdout,chs,ReadExit) != ReadExit) {
      perror("Error 8 :(write(fdout,chs,ReadExit) != ReadExit) :");
      exit(8);
    }
  }
  if (ReadExit == 0) { /* reached end of input file */
    if (ftruncate(fdout,ReadSize) != 0) {
      perror("Error 9 :(ftruncate(fdout,ReadSize) != 0) :");
      exit(9);
    }
  } else {
    perror("Error 10 : read(fdin,chs,MAXBSIZE) <0 :");
    exit(10);
  }
  exit(0);
}



More information about the Alt.sources mailing list