我正在尝试遍历 csv 文件行前行并将值分配给一个名为卡的结构。我的循环遍历文件添加分配值给卡 [x] 但每次我的代码循环虽然它不断更改旧值,如卡 [0];
#include "card.h"
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int main(int argc, char **argv) {
int num_entries = 0;
card_t **cards = NULL;
int freeCards = 0;
char *buf = NULL;
size_t bufsiz = 0;
int x = 0;
FILE *input_file = fopen("short-cards-1.csv", "r");
ssize_t result;
getline(&buf, &bufsiz, input_file);
while ( (result = getline(&buf, &bufsiz, input_file)) > 0){
num_entries++;
cards = realloc(cards, sizeof(card_t *) * num_entries);
cards[x] = malloc(sizeof(card_t));
printf("x: %d\n",x);
printf("===============\n" );
char *stringp = buf;
int id = atoi(strsep(&stringp, ","));
cards[x]->id = id;
printf("ID: %d\n", cards[x]->id);
//get name
stringp++;
cards[x]->name = strsep(&stringp, "\"");
printf("%s\n",cards[x]->name);
//get cost
stringp += 2;
//printf("Cost: %s\n",strsep(&stringp, "\""));
cards[x]->cost = strsep(&stringp, "\"");
printf("Cost: %s\n",cards[x]->cost);
printf("===================\n");
printf("ID: %d\n", cards[0]->id);
printf("Cost: %s\n",cards[0]->name);
printf("Cost: %s\n",cards[0]->cost);
printf("===============\n\n\n" );
x++;
}
printf("===============\n");
printf("%d \n",cards[0]->id);
freeCards = 0;
while (freeCards < num_entries){
free(cards[freeCards]);
freeCards++;
}
free(cards);
free(buf);
fclose(input_file);
return 0;
}
enum rarity
{
common,
uncommon,
rare,
mythic
};
typedef struct card
{
unsigned int id;
char* name;
char* cost;
unsigned int converted_cost;
char* type;
char* text;
char* stats;
enum rarity rarity;
} card_t;
output
x: 0
===============
ID: 198981
Stolen by the Fae
Cost: {X}{U}{U}
===================
ID: 198981
Cost: Stolen by the Fae
Cost: {X}{U}{U}
===============
x: 1
===============
ID: 192783
Eternal Isolation
Cost: {1}{W}
===================
ID: 198981
Cost: Eternal Isolation
Cost: {1}{W}
===============
x: 2
===============
ID: 192783
Eternal Isolation
Cost: {1}{W}
===================
ID: 198981
Cost: Eternal Isolation
Cost: {1}{W}
===============
x: 3
===============
ID: 192504
Corpse Knight
Cost: {W}{B}
===================
ID: 198981
Cost: Corpse Knight
Cost: B}
===============
x: 4
===============
ID: 183427
Orzhov Enforcer
Cost: {1}{B}
===================
ID: 198981
Cost: Orzhov Enforcer
Cost: }{B}
===============
当将新值分配给 card[x] 时,我的 card[0] 没有被更改,并且在第一次循环后 x 永远不会为 0;