/*Write a program that indefinitely takes in files to append to a master
file. If the file names are the same, don't do it. If there's an error,
don't do it. Exit with a blank line. Use a custom buffer.*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NAME 25
#define BUFSIZE 1024
int append(FILE *, FILE *);
int main(){
char src[MAX_NAME], mainfile[MAX_NAME];
FILE *src_ptr, *mainfile_ptr;
int successes = 0;
puts("Enter name of main file");
if(gets(mainfile) == NULL){
fprintf(stderr, "Error, couldn't get filename\n");
return 1;
}
if((mainfile_ptr = fopen(mainfile, "ab")) == NULL){
fprintf(stderr, "Error, couldn't open mainfile\n");
return 1;
}
do{
puts("Enter a filename to be appended");
if(gets(src) == NULL || src[0] == '\0' || strcmp(src, mainfile) == 0){
if(src[0])
puts("Error, couldn't get filename!");
continue;
}
if((src_ptr =fopen(src, "rb")) == NULL){
puts("Error, could not open file");
continue;
}
if(setvbuf(src_ptr, NULL, _IOFBF, BUFSIZE) != 0){
puts("Couldn't create filebuffer!");
continue;
}
if(append(src_ptr, mainfile_ptr) != 0){
fflush(src_ptr);
puts("Couldn't append!");
continue;
}
fclose(src_ptr);
++successes;
printf("Successfully appended %s, %d files total\n", src, successes);
}while(src[0] != '\0');
fclose(mainfile_ptr);
printf("Successfully appended %d files, bye!\n", successes);
return 0;
}
int append(FILE *src, FILE *mainfile){
size_t bytes = 0;
static char buffer[BUFSIZE];
while(bytes = (fread(buffer, sizeof(char), BUFSIZE, src)) > 0)
fwrite(buffer, sizeof(char), BUFSIZE, mainfile);
if(ferror(src) || ferror(mainfile))
return 1;
return 0;
}
你好呀。根据 C Primer Plus 示例,我编写了一个程序,它将用户指定文件的内容附加到主文件中。最初我编写它的目的只是为了将它与文本文件一起使用,但后来我将其更改为在二进制模式下工作。我用它来附加四个文件。我得到了一些非常奇怪的结果,我不知道为什么。这是完成文件的截图(我不得不截图,因为它充满了非常奇怪的字符)。我得到了相同的结果,而无需使用 fopen 以二进制模式打开它们。它似乎多次“附加”我的文件,其中一些只是一半,然后是另一半。
我哪里做错了?
我不知道为什么它调整了这么多。