append.c 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /* append.c -- appends files to a file */
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #define BUFSIZE 4096
  6. #define SLEN 81
  7. void append(FILE *source, FILE *dest);
  8. char * s_gets(char * st, int n);
  9. int main(void)
  10. {
  11. FILE *fa, *fs; // fa for append file, fs for source file
  12. int files = 0; // number of files appended
  13. char file_app[SLEN]; // name of append file
  14. char file_src[SLEN]; // name of source file
  15. int ch;
  16. puts("Enter name of destination file:");
  17. s_gets(file_app, SLEN);
  18. if ((fa = fopen(file_app, "a+")) == NULL)
  19. {
  20. fprintf(stderr, "Can't open %s\n", file_app);
  21. exit(EXIT_FAILURE);
  22. }
  23. if (setvbuf(fa, NULL, _IOFBF, BUFSIZE) != 0)
  24. {
  25. fputs("Can't create output buffer\n", stderr);
  26. exit(EXIT_FAILURE);
  27. }
  28. puts("Enter name of first source file (empty line to quit):");
  29. while (s_gets(file_src, SLEN) && file_src[0] != '\0')
  30. {
  31. if (strcmp(file_src, file_app) == 0)
  32. fputs("Can't append file to itself\n",stderr);
  33. else if ((fs = fopen(file_src, "r")) == NULL)
  34. fprintf(stderr, "Can't open %s\n", file_src);
  35. else
  36. {
  37. if (setvbuf(fs, NULL, _IOFBF, BUFSIZE) != 0)
  38. {
  39. fputs("Can't create input buffer\n",stderr);
  40. continue;
  41. }
  42. append(fs, fa);
  43. if (ferror(fs) != 0)
  44. fprintf(stderr,"Error in reading file %s.\n",
  45. file_src);
  46. if (ferror(fa) != 0)
  47. fprintf(stderr,"Error in writing file %s.\n",
  48. file_app);
  49. fclose(fs);
  50. files++;
  51. printf("File %s appended.\n", file_src);
  52. puts("Next file (empty line to quit):");
  53. }
  54. }
  55. printf("Done appending. %d files appended.\n", files);
  56. rewind(fa);
  57. printf("%s contents:\n", file_app);
  58. while ((ch = getc(fa)) != EOF)
  59. putchar(ch);
  60. puts("Done displaying.");
  61. fclose(fa);
  62. return 0;
  63. }
  64. void append(FILE *source, FILE *dest)
  65. {
  66. size_t bytes;
  67. static char temp[BUFSIZE]; // allocate once
  68. while ((bytes = fread(temp,sizeof(char),BUFSIZE,source)) > 0)
  69. fwrite(temp, sizeof (char), bytes, dest);
  70. }
  71. char * s_gets(char * st, int n)
  72. {
  73. char * ret_val;
  74. char * find;
  75. ret_val = fgets(st, n, stdin);
  76. if (ret_val)
  77. {
  78. find = strchr(st, '\n'); // look for newline
  79. if (find) // if the address is not NULL,
  80. *find = '\0'; // place a null character there
  81. else
  82. while (getchar() != '\n')
  83. continue;
  84. }
  85. return ret_val;
  86. }