gpt4 book ai didi

c - 什么是二进制文件的 EOF?

转载 作者:太空宇宙 更新时间:2023-11-04 00:37:03 24 4
gpt4 key购买 nike

我的程序需要从一个二进制文件读取到一个链表,这个函数做得很好,并为它分配了正确的内存,但由于某种原因,它在中断之前做了另一个循环。尝试为它寻找一个好的解决方案但没有运气,链表中的最后一个结构变得垃圾。

结构:

typedef struct
{
char id[10];
char * first_name;
char * last_name;
int age;
char gender;
char * username;
char * password;
char * description;
int hobbies[4];
struct Person * next_client;
}Person;

这里是一些代码:

Person * input_from_file(Person * member)
{
int str_size;
Person * clients_start = NULL;
FILE * filePointerRead;

filePointerRead = fopen("input.bin", "rb");

if (filePointerRead != NULL){
while (1){

member = NULL;
member = (Person*)malloc(sizeof(Person));

fread(&member->id, sizeof(char), ID_DIGITS + 1, filePointerRead);

fread(&str_size, sizeof(int), 1, filePointerRead);
member->first_name = (char*)malloc(str_size*sizeof(char));
fread(member->first_name, sizeof(char), str_size, filePointerRead);

//more reading from file

member->next_client = NULL;
clients_start = receive_clients_info(clients_start, member); //function to put the received struct from file to end of the linked list

if (feof(filePointerRead))
break;
}
fclose(filePointerRead);
}
return clients_start;
}

最佳答案

调用 feof 的问题在于,除非您在 EOF 处尝试读取,否则它不会返回“true”。换句话说,如果您的文件恰好有 100 个字节,并且您已经成功地尝试读取恰好 100 个字节,feof 将返回“false”,直到您尝试至少再读取一个字节。

这就是为什么你应该避免使用 feof 来检查 fread 的返回值的原因,它会告诉你从文件中读取了多少字节:

if (fread(&member->id, sizeof(char), ID_DIGITS + 1, filePointerRead) != ID_DIGITS + 1) {
// The code above knows that sizeof(char) is always 1.
// For other data types you need to compute the actual size
// by multiplying sizeof(T) by the number of items that you read.
break;
}

在你调用 fread 的所有地方做同样的事情。

!= 比较是有效的,因为 fread 在完成请求时总是返回您传递的确切大小:

Upon successful completion, fread() shall return the number of elements successfully read which is less than nitems only if a read error or end-of-file is encountered.

关于c - 什么是二进制文件的 EOF?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28056602/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com