JGuizard
8/3/2015 - 6:05 PM

fileio.c

#include <stdio.h>

// Only for solution 5
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#define BUFDIM 1024

int 
main (int argc, char **argv) { 
  FILE * fs, *fd;
  char c;
  char name[1024], buffer[1024];
  int count;

  // Solution 1
  sprintf (name, "%s.1", argv[2]);
  fs = fopen (argv[1], "r");
  fd = fopen (name, "w");
  while (fscanf(fs,"%c", &c) != EOF) {
    fprintf(fd, "%c", c);
  }
  fclose(fs);
  fclose(fd);

  // Solution 2
  sprintf (name, "%s.2", argv[2]);
  fs = fopen (argv[1], "r");
  fd = fopen (name, "w");
  while ((c = fgetc (fs)) != EOF) {
    fputc (c, fd);
  }
  fclose(fs);
  fclose(fd);
  
  // Solution 3
  sprintf (name, "%s.3", argv[2]);
  fs = fopen (argv[1], "r");
  fd = fopen (name, "w");
  while (fgets (buffer, 132, fs) != NULL) {
    fputs (buffer, fd);
  }
  fclose(fs);
  fclose(fd);


  // Solution 4
  sprintf (name, "%s.4", argv[2]);
  fs = fopen (argv[1], "rb");
  fd = fopen (name, "wb");
  while ((count = fread (buffer, 1, sizeof (buffer), fs)) != 0) {
    fwrite (buffer, 1, count, fd);
  }
  fclose(fs);
  fclose(fd);


  // Solution 5
  fs = open (argv[1], O_RDONLY);
  if (fs == -1){
    fprintf(stderr,"%s: cannot open file %s\n", argv[0], argv[1] );
    exit(-1);
  }

  /* create dest. file in read-write mode */
  sprintf (name, "%s.5", argv[2]);
  fd = creat (name, 0666);
  if (fd == -1) {
    fprintf(stderr, "%s: cannot create file %s\n",
      argv[0], name);
    exit (-1); 
  }

  while ((count = read( fs, buffer, BUFDIM)) > 0) {
    write (fd, buffer, count);
  }

  close (fs);
  close (fd);

  return (0);
}