【问题标题】:Passing argument 4 of fwrite from incompatible pointer type从不兼容的指针类型传递 fwrite 的参数 4
【发布时间】:2020-04-06 16:18:26
【问题描述】:

我想将源文件的内容复制到目标文件中,但收到以下警告:

warning: passing argument 4 of ‘fwrite’ from incompatible pointer type [-Wincompatible-pointer-types]

fwrite(target, sizeof(char), targetSize, sourceContent);

如果我忽略警告,我会遇到分段错误。

FILE *source = fopen(argv[1], "r");
FILE *target = fopen(argv[2], "w");

if (source == NULL || target == NULL) {
    printf("One or both files do NOT exist\n");
    abort();
}

fseek(source, 0, SEEK_END);
long sourceSize = ftell(source);

fseek(source, 0, SEEK_SET);
char *sourceContent = (char *)malloc(sourceSize);
fread(sourceContent, sizeof(char), sourceSize, source);


long targetSize = sourceSize;
fwrite(target, sizeof(char), targetSize, sourceContent);

【问题讨论】:

    标签: c fwrite gcc-warning


    【解决方案1】:

    fread() and fwrite() 都将要读取/写入的缓冲区作为 first 参数,将文件作为第四个参数。

    // This is fine.
    fread(sourceContent, sizeof(char), sourceSize, source);
    // Swap the first and fourth argument in the fwrite call.
    fwrite(sourceContent, sizeof(char), targetSize, target);
    

    【讨论】:

      猜你喜欢
      • 2016-01-27
      • 2011-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-25
      • 1970-01-01
      • 2016-03-28
      相关资源
      最近更新 更多