thể trùng lặp:
“while(!feof(file))” is always wrongC đọc tập tin nhị phân
Nếu tôi viết một mảng đến tập tin đầu ra và tôi đóng file, sau đó mở tập tin một lần nữa và đọc tất cả mọi thứ cho đến khi cuối -of-file là đạt được, mặc dù tập tin chỉ chứa 4 số, chương trình sẽ đọc và in 5 số, tại sao?
đầu ra chương trình:
a[0] = 4
a[1] = 7
a[2] = 12
a[3] = 34
a[4] = 34
save.bin (với một trình soạn thảo hex)
04000000 07000000 0C000000 22000000
#include <stdio.h>
#include <stdlib.h>
#define path "save.bin"
int main(void)
{
FILE *f=NULL;
int a[]={4,7,12,34},i,n=4,k;
f=fopen(path,"wb");
if(f==NULL)
{
perror("Error");
exit(1);
}
for(i=0;i<n;i++) // or I could use fwrite(a,sizeof(int),n,f);
fwrite(&a[i],sizeof(int),1,f);
fclose(f);
f=fopen(path,"rb");
if(f==NULL)
{
perror("Error");
exit(1);
}
i=0;
while(!feof(f))
{
fread(&k,sizeof(int),1,f);
printf("a[%d] = %d\n",i,k);
i++;
}
printf("\n");
fclose(f);
return 0;
}
Cảm ơn bạn rất nhiều !!! – Cristi