第 13 章 文件输入/输出 (把文件附加到另一个文件末尾)
程序员文章站
2022-03-14 10:05:23
1 /* 2 append.c -- 把文件附加到另一个文件末尾 3 */ 4 5 #include 6 #include 7 #include 8 9 #define BUFSIZE 4096 10 #define SLEN 81 1 ......
1 /*---------------------------------------- 2 append.c -- 把文件附加到另一个文件末尾 3 ----------------------------------------*/ 4 5 #include <stdio.h> 6 #include <stdlib.h> 7 #include <string.h> 8 9 #define BUFSIZE 4096 10 #define SLEN 81 11 12 void append(FILE *sourse, FILE *dest); 13 char *s_gets(char *st, int n); 14 15 int main() 16 { 17 FILE *fa, *fs; //fa 指向目标文件,fs指向源文件 18 int files = 0; //附加文件的数量 19 char file_app[SLEN]; //目标文件名 20 char file_src[SLEN]; //源文件名 21 int ch; 22 23 puts("Enter name of destination file:"); 24 25 s_gets(file_app, SLEN); 26 27 if ((fa = fopen(file_app, "a+")) == NULL) 28 { 29 fprintf(stderr, "Can't open %s\n", file_app); 30 exit(EXIT_FAILURE); 31 } 32 33 if (setvbuf(fa, NULL, _IOFBF, BUFSIZ) != 0) 34 { 35 fputs("Can't create output buffer\n", stderr); 36 exit(EXIT_FAILURE); 37 } 38 39 puts("Enter name of first source file (empty line to quit):"); 40 41 while (s_gets(file_src, SLEN) && file_src[0] != '\0') 42 { 43 if (strcmp(file_src, file_app) == 0) 44 fputs("Can't append file to itself\n", stderr); 45 else if ((fs = fopen(file_src, "r")) == NULL) 46 fprintf(stderr, "Can't open %s\n", file_src); 47 else 48 { 49 if (setvbuf(fs, NULL, _IOFBF, BUFSIZE) != 0) 50 { 51 fputs("Can't create input buffer\n", stderr); 52 continue; 53 } 54 55 append(fs, fa); 56 57 if (ferror(fs) != 0) 58 fprintf(stderr, "Error in reading file %s.\n", file_src); 59 60 if (ferror(fa) != 0) 61 fprintf(stderr, "Error in writint file %s.\n", file_app); 62 63 fclose(fs); 64 ++files; 65 printf("File %s appended.\n", file_src); 66 puts("Next file (empty line to quit):"); 67 } 68 } 69 70 printf("Done appending. %d files appended.\n", files); 71 rewind(fa); 72 printf("%s contents:\n", file_app); 73 while ((ch = getc(fa)) != EOF) 74 putchar(ch); 75 puts("Done displaying."); 76 fclose(fa); 77 78 return 0; 79 } 80 81 void append(FILE *sourse, FILE *dest) 82 { 83 size_t bytes; 84 static char temp[BUFSIZ]; //只分配一次内存 85 86 fwrite("\n", sizeof(char), strlen("\n") + 1, dest); 87 88 while ((bytes = fread(temp, sizeof(char), BUFSIZ, sourse)) > 0) 89 fwrite(temp, sizeof(char), bytes, dest); 90 } 91 92 char *s_gets(char *st, int n) 93 { 94 char *ret_val; 95 char *find; 96 97 if (ret_val = fgets(st, n, stdin)); 98 { 99 if (find = strchr(st, '\n')) //查找换行符 100 *find = '\0'; 101 else 102 while (getchar() != '\n') continue; 103 } 104 105 return ret_val; 106 }