提问人:adits2 提问时间:4/17/2017 更新时间:4/17/2017 访问量:128
调用 fread() 函数时文件指针如何移动?[复制]
How does file pointer shifts when fread() function is called? [duplicate]
问:
//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赞
Benoît
4/17/2017
#1
feof()
是用来知道你碰到什么样的错误,而不是检测一个。正确的方法是检查文件末尾的值返回值,该值为 0。然后,如果为 true,则知道已达到 EOF,否则会出现 IO 错误。fread()
feof()
因此,使用当前代码,您处理的可读记录是上一个可读记录的两倍。另外,你的意思是而不是.&h[0]
&h
评论
std
在 C++ 中称呼某物是一个可怕的名字。