append.c 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4. int main( int ac , char *av[] )
  5. {
  6. // print the help flag thing
  7. if ( (ac < 2 ) || ( ! strcmp (av[1], "--help") ) ) {
  8. printf ("%s\n", "This program appends a source file to a destination file.");
  9. printf ("%s\n", "syntax:");
  10. printf ("\t%s\n", "append DESTINATION SOURCE");
  11. } else {
  12. if (ac < 3) {
  13. printf ("%s\n", "Destination file must be provided.");
  14. printf ("%s\n", "See 'append --help'.");
  15. return 1;
  16. } else {
  17. // av[1] is destination
  18. // av[2] is source
  19. FILE *destination, *source;
  20. // open the source file
  21. source = fopen (av[2], "r");
  22. // error if there is no source
  23. if ( !source ) {
  24. printf ("Error: Source file '%s' not found.\n", av[2]);
  25. return 1;
  26. }
  27. // buffer for reading
  28. char buffer[128];
  29. // open (or create) the destination file
  30. destination = fopen (av[1], "a");
  31. // read into buffer and write to file
  32. while (fgets (buffer, sizeof (buffer), source)) {
  33. fprintf (destination, "%s", buffer);
  34. }
  35. // clean up
  36. fclose (source);
  37. fclose (destination);
  38. }
  39. }
  40. return 0;
  41. }