0
嗨,我試圖從一個文件中讀寫一個整數數組,但是,我正在使用的循環讀取它們是在一個無限循環中。我將如何修復這個無限循環,以便當它到達文件末尾時退出循環。另外,我不完全確定fread是否按照我期望的那樣做。從二進制文件寫入和讀取整數數組
FILE *fptr = fopen("number.db", "wb");
int nums[100] = {1,2,3,4,5,6,7,8,9,100,101,102,103,104,105};
int nums2[100];
fwrite(nums,sizeof(int),15,fptr);
fclose(fptr);
fptr = fopen("number.db", "rb");
fseek(fptr,0,SEEK_END);
long end = ftell(fptr); //finds length of the file
fseek(fptr,0,SEEK_SET);
while(!feof(fptr)){
int counter = 0;
fread(nums2,sizeof(int),1,fptr);
fseek(fptr,counter,SEEK_SET);
counter++;
if(counter>=end){ //Breaks when it seeks to the end
break;
}
fclose(fptr);
我覺得有一些與fread的邏輯,但我不太確定。當我打印出保存在「nums2」中的數字時,它只能讀取最後一個數字:對於nums2的所有元素,都是105。
這是無限循環,因爲你是在循環每次初始化'counter'爲0,'fseek'以指針到文件的開頭。取出'int counter = 0;'在循環外 – kuro
和'fread(nums2,sizeof(int),1,fptr);' - >'fread(nums2 + counter,sizeof(int),1,fptr); ',需要'end/= sizeof(int);' – BLUEPIXY