读文件时,使用feof()判断文件是否结束,使用时发现文件最后的数据会重复出现一次,比较令人费解!
源代码:
#include<stdio.h>
#include <stdlib.h>
struct BlockInfo
{
int index;
int started;
int length;
};
void main()
{
BlockInfo infoContinue;
FILE* assistFile;
char* str = "sqx.txt";
assistFile = fopen(str,"wb");
if (assistFile == NULL)
{
printf("%s/n","create assist file failed!");
}
for (int i = 0 ; i < 2 ;i ++)
{
infoContinue.index = i;
infoContinue.started = i+10;
infoContinue.length = i*10;
fwrite(&infoContinue,sizeof(struct BlockInfo),1,assistFile);
}
fclose(assistFile);
FILE* readFile;
readFile = fopen(str , "r+");
while(!feof(readFile))
{
fread(&infoContinue,sizeof(struct BlockInfo),1,readFile);
printf("%s%d/n" , "数据块索引 = " , infoContinue.index);
}
fclose(readFile);
}
输出:
数据块索引 = 0
数据块索引 = 1
数据块索引 = 1(重复输出!!!!!!)
分析:
1. 最后的数据会重复输出是因为feof在遇到文件结束符EOF这个位置时,返回的还是0,而到下一个位置时才返回1,这时while循环才退出。所以单纯用上面的while循环判断会出现重复的现象。
2. 使用feof()时,要先读文件然后使用feof()判断文件是否结束。即:
while(1)
{
fread();
if(feof()) break;
}
修改后代码:
#include<stdio.h>
#include <stdlib.h>
#include <fstream>
#include <iostream>
using namespace std;
struct BlockInfo
{
int index;
int started;
int length;
};
void main()
{
BlockInfo infoContinue;
FILE* assistFile;
char* str = "sqx.txt";
assistFile = fopen(str,"wb");
if (assistFile == NULL)
{
printf("%s/n","create assist file failed!");
}
for (int i = 0 ; i < 2 ;i ++)
{
infoContinue.index = i;
infoContinue.started = i+10;
infoContinue.length = i*10;
fwrite(&infoContinue,sizeof(struct BlockInfo),1,assistFile);
}
fclose(assistFile);
FILE* readFile;
readFile = fopen(str , "r+");
while(1)
{
fread(&infoContinue,sizeof(struct BlockInfo),1,readFile);
if (feof(readFile))
{
break;
}
printf("%s%d/n" , "数据块索引 = " , infoContinue.index);
}
fclose(readFile);
}
输出:
数据块索引 = 0
数据块索引 = 1