如何在我的程序中正确使用fread()和fwrite()?

时间:2013-07-30 16:45:33

标签: c file io fwrite fread

/*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在二进制模式下打开它们。它似乎“追加”我的文件 多次,其中一些只有一半,然后是另一半。

我哪里出错了?

File being viewed in gvim

我不知道为什么它如此重新调整大小。

1 个答案:

答案 0 :(得分:9)

while(bytes = (fread(buffer, sizeof(char), BUFSIZE, src)) > 0)
    fwrite(buffer, sizeof(char), BUFSIZE, mainfile); 

应该是

while((bytes = fread(buffer, sizeof(char), BUFSIZE, src)) > 0)
    fwrite(buffer, sizeof(char), bytes, mainfile);

fread返回小于BUFSIZE字节的情况下,您将先前读取的数据写入mainfile

您还可以检查fwrite是否返回bytes,选择是否中止或重试写入缓冲区的剩余部分。