在结构体中分配 CSV 列 - 分配
typedef struct { // Define columns of CSV file as members of the struct char name[100]; int age; float height; } Person;
FILE *fp = fopen("people.csv", "r"); // Open CSV file for reading char line[1024]; Person person_array[100]; // Create an array of Person structs int count = 0; while (fgets(line, 1024, fp)) { // Parse CSV line into struct members and allocate to array sscanf(line, "%[^,],%d,%f", person_array[count].name, &person_array[count].age, &person_array[count].height); count++; }
fclose(fp); // Use allocated Person structs for (int i = 0; i < count; i++) { printf("Name: %s, Age: %d, Height: %f\n", person_array[i].name, person_array[i].age, person_array[i].height); }