无法保证会为fread
您提供您要求的所有字节。它可以给你更少的东西,这就是返回码的用途。
您需要使用返回码来确定要发送多少信息到fwrite
.
并且对返回码的检查也延伸到了fopen
调用——不能保证 open 会起作用。
例如,下面的完整程序将尝试将最多 3K 从一个文件复制到另一个文件:
#include <stdio.h>
#include <errno.h>
int main (void) {
FILE *fp1, *fp2;
char buff[3*1024];
int bytesRead;
// Open both files.
if ((fp1 = fopen ("a.txt", "r")) == NULL) {
printf ("Error %d opening a.txt\n", errno);
return 1;
}
if ((fp2 = fopen ("b.txt", "w")) == NULL) {
printf ("Error %d opening b.txt\n", errno);
fclose (fp1);
return 1;
}
// Transfer only up to buffer size.
if ((bytesRead = fread (buff, 1, sizeof (buff), fp1)) == 0) {
// Check error case.
if (ferror (fp1)) {
printf ("Error reading a.txt\n");
fclose (fp1);
fclose (fp2);
return 1;
}
}
// Attempt transfer to destination file.
if (fwrite (buff, 1, bytesRead, fp2) != bytesRead) {
printf ("Error writing b.txt\n");
fclose (fp1);
fclose (fp2);
return 1;
}
// Close all files to finish up.
fclose (fp1);
fclose (fp2);
return 0;
}