gpt4 book ai didi

c - 如何将信息从 txt 文件传输到结构的动态 vector

转载 作者:行者123 更新时间:2023-11-30 20:57:53 25 4
gpt4 key购买 nike

我正在尝试将驱动程序的信息从 txt 文件传输到结构的动态 vector 。我有一个像这样的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

第一行是司机的名字,第二行是司机的身份证、出生日期、体重、经历和处罚。

我需要创建带有动态 vector 的结构来保存每个驱动程序的信息,但我的问题是动态 vector 。有人可以帮我吗?

最佳答案

它是动态分配的数组,使用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 #%d\n", 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=%d\n",
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个元素,然后在需要时再realloc多一个元素,以获得更好的性能,以防有最终数组中有很多元素。

警告drivers = realloc(drivers, ...)可以或不移动分配的数组以便能够找到更多空间,但您总是需要假设它的地址发生变化,这就是为什么我在 drivers

中重新分配结果

关于c - 如何将信息从 txt 文件传输到结构的动态 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55819158/

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