c - 从 C 中的文件读取时,最后一个对象重复两次
问题描述
我在 C 中有一个结构,我将其对象写入 C 中的文件,同时再次读取同一个文件,最后一个对象被重复两次。我该如何解决这个问题,为什么会这样?
#include<stdio.h>
#include<string.h>
typedef struct car {
int id;
char *name;
int price;
char *colors[5];
} car;
int main()
{
car obj1 = { .id = 5,
.name = "honda city zx",
.price = 1500,
.colors = {"red", "black", "blue"}
};
car obj2 = { .id = 6,
.name = "honda city",
.price = 2500,
.colors = {"lal", "kala", "neela"}
};
FILE *fp;
fp = fopen("car_details.dat", "w");
fwrite(&obj1, sizeof(obj1), 1, fp);
fwrite(&obj2, sizeof(obj2), 1, fp);
fclose(fp);
fp = fopen("car_details.dat", "r");
car obj;
while(!feof(fp))
{
fread(&obj, sizeof(obj), 1, fp);
printf("id : %d\nname : %s\nprice : %d\ncolors : {%s, %s, %s}\n", obj.id, obj.name, obj.price, obj.colors[0], obj.colors[1], obj.colors[2]);
}
return 0;
}
输出是:
id : 5
name : honda city zx
price : 1500
colors : {red, black, blue}
id : 6
name : honda city
price : 2500
colors : {lal, kala, neela}
id : 6
name : honda city
price : 2500
colors : {lal, kala, neela}
然而,预期的输出是每个要打印一次的对象。
id : 5
name : honda city zx
price : 1500
colors : {red, black, blue}
id : 6
name : honda city
price : 2500
colors : {lal, kala, neela}
所以我的问题是为什么会发生这种情况,我该如何解决?
编辑:当我尝试在循环内打印指针的位置时
while(!feof(fp))
{
fread(&obj, sizeof(obj), 1, fp);
printf("The pointer is at %ld\n", ftell(fp));
printf("id : %d\nname : %s\nprice : %d\ncolors : {%s, %s, %s}\n\n", obj.id, obj.name, obj.price, obj.colors[0], obj.colors[1], obj.colors[2]);
}
我得到:
The pointer is at 64
{object}
The pointer is at 128
{object}
The pointer is at 128
{object}
这怎么可能?我已经读过,每当 fread 读取流时,它会在读取那么多字节后移动指针。因此,当这次循环第二次运行时,它应该将文件指针移动到文件末尾,但它没有。为什么会这样?我缺乏任何概念吗?请原谅我是初学者!
解决方案
推荐阅读
- wordpress - Wordpress - dynamic_sidebar - 导致加载 XML 时出错
- jquery - 基于 jQuery 的文本搜索/过滤器有效,但不适用于所有字段
- java - 文件提供程序 Uri 错误
- mongodb - 根据 Mongodb 中字段的平均值计算文档
- php - 从下拉php中抓取数据
- mysql - l mysql为什么打不开unix socket lock文件?
- python - 如何从 AWS Lambda 在客户端打开 URL?
- php - 当我选择图像时,图像名称应使用 jquery 显示
- android-sqlite - 如何腾出空间将单个记录插入数据库?
- apache-spark - 如何在 Spark Databricks 中注册 SQL 函数