File Input/Output


Simple File copy in C Here is a very simple file copy program in C.

File Copy Program in C Runs of File Copy Program
#include <stdio.h>

int main(int argc, char *argv[]) {
   int ch;
   FILE *infile, *outfile;
   infile = fopen("source.txt", "r");
   if (infile == NULL) {
      fprintf(stderr, "Can't open %s\n", "source.txt");
      exit(1);
   }
   outfile = fopen("dest.txt", "w");
   while ((ch = fgetc(infile)) != EOF)
      fputc(ch, outfile);
}
% cc -o filecopy filecopy.c
% rm dest.txt
% cat source.txt
Where are you?
% filecopy
% cat dest.txt
Where are you?
% rm source.txt
% filecopy
Can't open source.txt


File copy in C The following program is a fairly sophisticated file copy program in C, but it is essentially the same as the previous one.

File Copy Program in C Runs of File Copy Program
#include <stdio.h>

void filecopy(FILE *infile, FILE *outfile);

int main(int argc, char *argv[]) {
   FILE *infile, *outfile;
   if (argc == 1) /* copy stdin to stdout */
      filecopy(stdin, stdout);
   else {  // argc > 1
      if ((infile = fopen(*++argv, "r")) == NULL) {
         fprintf(stderr, "Can't open %s\n", *argv);
         exit(1);
      }
      if (argc == 2) {
         filecopy(infile, stdout);
         fclose(infile);
      }
      else if (argc == 3) {
         if ((outfile = fopen(*++argv, "w")) == NULL) {
            fprintf(stderr, "Can't open %s\n", *argv);
            exit(1);
         }
         filecopy(infile, outfile);
         fclose(infile);
         fclose(outfile);
      }
      else
         fprintf(stderr, "Extra CL args\n", *argv);
   }
}

void filecopy(FILE *infile, FILE *outfile) {
   int ch;
   while ((ch = fgetc(infile)) != EOF)
      fputc(ch, outfile);
}
% cc -o copy copy.c
% copy
Where are you? [Enter Ctrl-D]
Where are you?
% cat source.txt
Where are you?
% copy < source.txt
Where are you?
% copy < source.txt > dest.txt
% cat dest.txt
Where are you?
% copy source.txt
Where are you?
% rm dest.txt
% copy source.txt dest.txt
% cat dest.txt
Where are you?
% copy source.txt dest.txt xyz
Extra CL args


Copyright © 2011, Neal R. Wagner. Permission is granted to access, download, share, and distribute, as long as this notice remains.