非常简单的fread fwrite问题



我一直在尝试如何使用fread和fwrite读取文件指针,但没有成功。我正在创建一个非常简单的程序来读取文件,使用fseek和ftell来确定大小,最后将第一个文件的内容写入第二个文件。我的代码编译但没有输出,我认为这是由于我有错误的fwrite函数造成的??

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
    FILE *infp;
    FILE *outp;
    char *str;
    size_t place;
    infp = fopen(argv[1], "r");
    if (infp==NULL) 
    {
        fputs ("File error",stderr); 
        exit (1);
    }
    outp = fopen(argv[2], "w");
    int count = 0;
    fseek(infp,0,SEEK_END);
    long size = ftell(infp);
    rewind(infp);
    str = (char *)malloc(sizeof(char)*size);
    if (str == NULL)
    {
        fputs("Memory error",stderr);
        exit(2);
    }
    place = fread(str, sizeof(char), size, infp);
    if (place != size) 
    {
        fputs ("Reading error",stderr); 
        exit (3);
    }
    fwrite(str, 1, place, infp);
    fclose(infp);
    fclose(outp);
    free(str);
}

您有一个打字错误。更改:

fwrite(str, 1, place, infp);

收件人:

fwrite(str, 1, place, outp);

最新更新