我正在尝试将驱动程序的信息从txt文件传输到结构的动态向量。我有一个这样的txt文件:
Paulo Andrade
2 23 12 1995 76 0.5 0
Faisca
3 1 1 1980 50 9.5 1
Diana Alves Pombo
4 1 10 1990 55 4.5 0
Ana Luisa Freitas
7 12 7 1976 68 1.0 3
第一行是司机的名字,第二行是他的身份证、出生日期、体重、经历和惩罚。
我需要使用动态向量创建结构以保存每个驱动程序的信息,但我的问题是动态向量。有人可以帮我吗?
它是一个动态分配的数组,使用 malloc 然后 realloc 来更改(增加(其大小
例如:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct Driver {
char * name;
int ID;
int day;
int month;
int year;
int weight;
float experience;
int punishment;
} Driver;
int main(int argc, char ** argv)
{
if (argc != 2) {
printf("Usage : %s <file>n", *argv);
return -1;
}
FILE * fp = fopen(argv[1], "r");
if (fp == NULL) {
fprintf(stderr, "cannot open '%s'n", argv[1]);
return -1;
}
char line[128];
Driver * drivers = malloc(0); /* initial allocation, here empty */
int n = 0;
while (fgets(line, sizeof(line), fp) != NULL) {
/* remove n */
char * p = strchr(line, 'n');
if (p != NULL)
*p = 0;
drivers = realloc(drivers, (n + 1) * sizeof(Driver)); /* resize to add one element */
Driver * d = &drivers[n++];
d->name = strdup(line);
if ((fgets(line, sizeof(line), fp) == NULL) ||
(sscanf(line, "%d %d %d %d %d %f %d",
&d->ID, &d->day, &d->month, &d->year,
&d->weight, &d->experience, &d->punishment)
!= 7)) {
fprintf(stderr, "invalid file driver #%dn", n);
fclose(fp);
return -1;
}
}
fclose(fp);
/* check */
Driver * sup = drivers + n;
for (Driver * d = drivers; d != sup; ++d)
printf("%s : ID=%d birthdate=%d/%d/%d weight=%d experience=%f punishment=%dn",
d->name, d->ID,
d->day, d->month, d->year,
d->weight, d->experience, d->punishment);
return 0;
}
编译和执行:
pi@raspberrypi:/tmp $ gcc -g -pedantic -Wextra -Wall d.c
pi@raspberrypi:/tmp $ cat f
Paulo Andrade
2 23 12 1995 76 0.5 0
Faisca
3 1 1 1980 50 9.5 1
Diana Alves Pombo
4 1 10 1990 55 4.5 0
Ana Luisa Freitas
7 12 7 1976 68 1.0 3
pi@raspberrypi:/tmp $ ./a.out f
Paulo Andrade : ID=2 birthdate=23/12/1995 weight=76 experience=0.500000 punishment=0
Faisca : ID=3 birthdate=1/1/1980 weight=50 experience=9.500000 punishment=1
Diana Alves Pombo : ID=4 birthdate=1/10/1990 weight=55 experience=4.500000 punishment=0
Ana Luisa Freitas : ID=7 birthdate=12/7/1976 weight=68 experience=1.000000 punishment=3
pi@raspberrypi:/tmp $
最初的malloc(0)
可能看起来很奇怪,但在使用 realloc 之后需要它,或者如果您愿意,请Driver * drivers = NULL;
。我每次只分配一个条目,最初也可以 malloc 超过 0,然后在必要时重新定位多个元素以获得更好的性能,以防最终数组中有很多元素。
警告drivers = realloc(drivers, ...)
可以或不移动分配的数组以找到更多空间,但您始终需要假设其地址更改,这就是我在驱动程序中重新分配结果的原因