首页 文章

调用fread()函数时文件指针如何移动? [重复]

提问于
浏览
0

这个问题在这里已有答案:

//Libraries are called accordingly 
struct std    
{
int a;
char b;
}// a structure with 2 objects

void main()

{

std h[5]; // structure array with 5 elements
int rec_size; // Size of single record to be accessed from the file 
rec_size=sizeof(structure std); // stores the size in bytes

while (true) 
  {
     fread(&h,rec_size,2,fptr); //fptr is a file pointer to some file

    /*Assume that the file pointer(fptr)has covered the last two record 
      blocks and stored
      them in "h". Then the shouldn't the position pointer proceed to end of 
      file and the next statement "if(feof(fptr)" then becomes true to exit 
      the loop and in essence miss out on the processing of those last two 
      record blocks?*/

    if(feof(fptr)) 
     /* Here, if the fptr has reached the end of file after fread(), 
        then this should execute*/                           
      break;

   //else additional code to process the content stored in "h" 
  }
}

我怀疑是当fread()函数返回并且在下一个语句中feof()检查EOF时,如果fread()处理文件中的最后两个记录块,feof()是否应该返回true?有人可以完全解释这个功能吗?

1 回答

  • 0

    feof() 用于了解您遇到的错误类型,而不是检测错误 . 正确的方法是检查 fread() 的值返回值,该值在文件末尾为0 . 然后,如果 feof() 为真,则表示您已达到EOF,否则出现IO错误 .

    因此,使用当前代码,您将处理最后可读记录的两倍 . 另外,你的意思是 &h[0] 而不是 &h .

相关问题