fread() 读不到EOF?

Nofico 2013-07-25 02:51:01
#include <stdio.h>
#define RECORD_LENGTH_ sizeof(char)*20+sizeof(unsigned int)+sizeof(double)

typedef struct RECORD_TAG{
unsigned int record_number;
long index_n; //
Detailed_record *record;
struct RECORD_TAG *fwd;
struct RECORD_TAG *bwd;
} Index;

Index index_entry;

int create_index(FILE *file_stream){
Index *new_node;
Index *current_node=&index_entry;
Index *previous_node=NULL;

rewind(file_stream);
while(!feof(file_stream)){
new_node=malloc(sizeof(Index));
if(new_node==NULL){
free_all_nodes();//如果动态分配内存失败,释放所有已分配的内存
printf("No enough memory!\n");
return 1;
}


current_node->fwd=new_node;
current_node->bwd=previous_node;
new_node->bwd=(current_node==&index_entry?NULL:current_node);
new_node->fwd=NULL;

previous_node=current_node;
current_node=current_node->fwd;

new_node->index_n=ftell(file_stream);
new_node->record=NULL;
fread(&new_node->record_number,sizeof(unsigned int),1,file_stream);
fseek(file_stream, RECORD_LENGTH_, SEEK_CUR);
}
index_entry.bwd=new_node;
return 0;
}


补充::FILE *file_stream=fopen("C:\db","a+b");。

现在的问题是,文件里面的记录为:

000000 01000000 20666666 20202020 20202020 *.... fff *
000016 20202020 20202020 0C000000 9A999999 * ........*
000032 99D95E40 01000000 2033322E 20202020 *..^@.... 32. *
000048 20202020 20202020 20202020 21000000 * !...*
000064 9A999999 99193640 02000000 20333320 *......6@.... 33 *
000080 20202020 20202020 20202020 20202020 * *
000096 2C000000 00000000 00803640 03000000 *,.........6@....*
000112 20637265 75687520 20202020 20202020 * creuhu *
000128 20202020 63000000 00000000 00C05440 * c.........T@*


前面的00....是十进制数值。调试时,ftell(file_stream)达到144以后,feof(file_stream)仍返回0;之后无论如何feof()都返回0。这是什么原因?望指点。
...全文
274 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
Nofico 2013-07-26
  • 打赏
  • 举报
回复
引用 5 楼 qzf362269994 的回复:
在读完文件的最后一个字符后,fp->flag仍然没有被置为_IOEOF,因而feof()仍然没有探测到文件结尾。直到再次调用fgetc()执行读操作,feof()才能探测到文件结尾。这样就多执行了一次。 对于feof()这个函数, 它是先读再判断是否到文件尾, 也就是说在它之前一定要读一次才能做出判断。
的确,我把代码改成

while((ch=fgetc(file_stream))!=EOF){
    ungetc(ch,file_stream);
}
就没有任何问题了。谢谢!
qzf362269994 2013-07-25
  • 打赏
  • 举报
回复
在读完文件的最后一个字符后,fp->flag仍然没有被置为_IOEOF,因而feof()仍然没有探测到文件结尾。直到再次调用fgetc()执行读操作,feof()才能探测到文件结尾。这样就多执行了一次。 对于feof()这个函数, 它是先读再判断是否到文件尾, 也就是说在它之前一定要读一次才能做出判断。
水平不流 2013-07-25
  • 打赏
  • 举报
回复
去掉fseek,应该可以正确.
图灵狗 2013-07-25
  • 打赏
  • 举报
回复
fseek会移动指针。
hzhxxx 2013-07-25
  • 打赏
  • 举报
回复
fopen fseek ftell
hzhxxx 2013-07-25
  • 打赏
  • 举报
回复
不需要这样读,先判断文件长度,然后一次把文件读进去。

33,311

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 新手乐园
社区管理员
  • 新手乐园社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧