C - 使用 fread 命令后二进制文件中的指针



im目前正在学习文件指针,并遇到了这个作为示例给出的代码 我尝试在Visual Studio中复制它,但是我不断收到目前不相关的运行时错误

void main()
{ 
FILE *cfPtr; /* credit.dat file pointer */
/* create clientData with default information */
struct clientData client = { 0, "", "", 0.0 };
if ( ( cfPtr = fopen( "credit.dat", "rb" ) ) == NULL ) 
printf( "File could not be opened.n" );
else { 
printf( "%-6s%-16s%-11s%10sn", "Acct", "Last Name",
"First Name", "Balance" );
/* read all records from file (until eof) */
fread( &client, sizeof( struct clientData ), 1, cfPtr );
while ( !feof( cfPtr ) ) { 
/* display record */
if ( client.acctNum != 0 ) 
printf( "%-6d%-16s%-11s%10.2fn", 
client.acctNum, client.lastName, 
client.firstName, client.balance );
fread( &client, sizeof( struct clientData ), 1, cfPtr );
} /* end while */
fclose( cfPtr ); /* fclose closes the file */
} /* end else */
} /* end main */

我的问题是,如果文件为空,结构客户端包含什么? 此外,如果在他们使用的代码中文件只有 1 个结构,那么指针不会移动到结构之后,这意味着它将位于 EOF 上,当他们使用时,如果它是假的,这意味着结构没有打印在屏幕上?

我的问题是,如果文件为空,结构客户端包含什么? 此外,如果在他们使用的代码中文件只有 1 个结构,则指针不会移动到结构之后,这意味着它将位于 EOF 上,当他们使用时,如果它是假的,这意味着结构没有打印在屏幕上?

7.21.8.1 面包函数
...
剧情简介

1
#include <stdio.h>
size_t fread(void * restrict ptr,
size_t size, size_t nmemb,
FILE * restrict stream);
描述

2fread函数读取ptr指向的数组中,最多读取nmemb个元素 其大小由size指定,来自stream指向的流。对于每个 对象,size调用fgetc函数和存储的结果,按顺序 读取,在unsigned char数组中精确地覆盖对象。文件位置 流的指示器(如果已定义)成功前进字符数 读。如果发生错误,则流的文件位置指示器的结果值为 定。如果读取部分元素,则其值不确定。

返回

3fread函数返回成功读取的元素数,可能是 如果遇到读取错误或文件末尾,则小于nmemb。如果sizenmemb为零,fread返回零,数组的内容和流的状态保持不变 变。
添加了 C 2011 在线草稿

强调; 如果fread返回此代码小于 1 的内容,则应假定client不包含任何有意义的内容。

切勿使用feof作为循环条件 - 在您尝试读取文件末尾之前,它不会返回 true,因此循环将过于频繁地执行一次。 相反,请像这样检查输入操作的结果:

while ( fread( &client, sizeof client, 1, cfPtr ) == 1 )
{
// process client normally
}
if ( feof( cfPtr ) )
fputs( "End of file detected on inputn", stderr );
else
fputs( "Error on inputn", stderr );

最新更新