Advertisement
puppet106

unite.c

Feb 28th, 2020
386
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.44 KB | None | 0 0
  1. // unite files to one
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <sys/stat.h>
  5. #include <fcntl.h>
  6. #include <unistd.h>
  7. #include <string.h>
  8.  
  9. #define MAXNAME 100
  10.  
  11. // routines
  12. void showusage();
  13. void diskwritefailure();
  14.  
  15. // constants & variables
  16. char *myname;
  17.  
  18. int main(int argc, char *argv[])
  19. {
  20.   int i, c, infile, outfile;
  21.   char buf[BUFSIZ], destinationfilename[MAXNAME];
  22.   size_t nread, nwrite;
  23.   strcpy((myname=malloc(sizeof(argv[0]))), argv[0]);
  24.  
  25.     // parse command line options
  26.     while ((c=getopt(argc, argv, ":o:")) != -1)
  27.      switch (c) {
  28.       case 'o':
  29.        strcpy(destinationfilename, optarg);
  30.       break;
  31.       case '?':
  32.        showusage();
  33.       break;
  34.       default:
  35.        abort();
  36.     break; }
  37.     if (argc<3)
  38.      showusage();
  39.     if ((outfile=open(destinationfilename, O_WRONLY| O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR))==-1)
  40.      diskwritefailure();
  41.  
  42.    // unite files
  43.    for (i=optind;i<argc;i++) {
  44.     if ((infile=open(argv[i], O_RDONLY))==-1)
  45.      break;
  46.     while ((nread=read(infile, buf, sizeof(buf))))
  47.      if ((nwrite=write(outfile, buf, nread)==-1))
  48.     diskwritefailure();
  49.    close(infile); }
  50.    close(outfile);
  51.    
  52.  return 0;
  53. }
  54.  
  55. // show usage
  56. void showusage()
  57. {
  58.   printf("%s [-o output file] [files ...]\n", myname);
  59.    
  60.  exit(EXIT_FAILURE);
  61. }
  62.  
  63. // error writing to disk
  64. void diskwritefailure()
  65. {
  66.   printf("error writing to disk!\n");  
  67.    
  68.  exit(EXIT_FAILURE);
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement