我有这个适用于我的代码:
fp = fopen("person.dat", "rb");
struct Person{
int pnummer;
char name[20];
float lenght;
float weight;
};
struct Person*object=malloc(sizeof(struct Person));
fread(object, sizeof(struct Person), 1, fp);
printf("%s\n%d\n%f\n%f\n",object->name,object->pnummer,object->lenght,object->weight);
输出: 安德烈亚斯 660311 181.000000 82.000000
我想读一下这个结构的数组。这样我就可以有10个人。我怎么写最后3行?
typedef struct{
int pnummer;
char name[20];
float lenght;
float weight;
}Person;
Person p_lista[10];
答案 0 :(得分:4)
Person p_lista[10];
...
fread(p_lista, sizeof(struct Person), 10, fp);
为简单起见,没有错误检查。
答案 1 :(得分:2)
以下是阅读和写作的完整代码
#include <stdio.h>
#include <stdlib.h>
struct Person {
int pnummer;
char name[20];
float lenght;
float weight;
};
int main(void) {
FILE* fp;
int i;
int count = 10;
/* let's say we have array of 10 persons */
struct Person src[10] = {
{ 1, "John", 1, 1},
{ 2, "Mary", 2, 2},
{ 3, "Charles", 4, 3},
{ 4, "Arnold", 5, 4},
{ 5, "Ted", 3, 5},
{ 6, "Rachel", 5, 6},
{ 7, "David", 6, 7},
{ 8, "Jim", 7, 8},
{ 9, "Alan", 8, 9},
{10, "Lisa", 9, 0},
};
/* write 10 persons to file */
fp = fopen("person.dat", "wb");
fwrite(src, sizeof(struct Person), count, fp);
fclose(fp);
/* read 10 persons to file */
fp = fopen("person.dat", "rb");
struct Person* objects = malloc(count * sizeof(struct Person));
fread(objects, sizeof(struct Person), count, fp);
fclose(fp);
/* output result */
for(i = 0; i < 10; ++i) {
printf("%s\n%d\n%f\n%f\n", objects[i].name, objects[i].pnummer, objects[i].lenght, objects[i].weight);
}
/* Without dynamic memory allocation */
struct Person p_lista[10];
/* number of persons to read */
int size = sizeof(p_lista) / sizeof(struct Person);
fp = fopen("person.dat", "rb");
fread(p_lista, sizeof(struct Person), size, fp);
fclose(fp);
/* output result */
for(i = 0; i < 10; ++i) {
printf("%s\n%d\n%f\n%f\n", p_lista[i].name, p_lista[i].pnummer, p_lista[i].lenght, p_lista[i].weight);
}
return 0;
}