我用 C 编写管理系统。我有这个结构
#define STRING_LENGTH 32
typedef struct {
char name[STRING_LENGTH];
} Name;
typedef struct{
int id, balance;
Name clientName;
} Client;
我创建了几个测试对象,打开二进制文件进行写入,用于fwrite
将对象写入文件,关闭它并在此之后使用fread
到while(!feof...
块中,我的问题是我将 4 个对象打印到二进制文件,而我从文件中读取对象并打印它到屏幕上,最后一个对象打印了两次。我做错了什么?我只需要将对象写入文件,然后从中取回它们。
我的代码:
FILE *clientsFile = NULL;
switch (selectedOption)
{
case CLIENT:
clientsFile = fopen(CLIENTS_FILE_PATH, "wb");
Client getUser;
Client temp1 = { 1, 10000, "Alex" };
Client temp2 = { 2, 100000, "Valery" };
Client temp3 = { 3, 105466, "Jack" };
Client temp4 = { 4, 1069640, "Pam" };
fwrite(&temp1, sizeof(Client), 1, clientsFile);
fwrite(&temp2, sizeof(Client), 1, clientsFile);
fwrite(&temp3, sizeof(Client), 1, clientsFile);
fwrite(&temp4, sizeof(Client), 1, clientsFile);
fclose(clientsFile);
clientsFile = fopen(CLIENTS_FILE_PATH, "rb");
do
{
fread(&getUser, sizeof(Client), 1, clientsFile);
printf("ID : %d, Name : %s, Balance : %d\n", getUser.id, getUser.clientName.name, getUser.balance);
} while (!feof(clientsFile));
break;
输出照片:输出画面
感谢您的回答