我想读一个.csv
的文件.我已经学习了解析和使用strtok
来解析.我也已经写了代码,但我的代码不能正常工作.我的代码只读取了一部分数据到 struct 体的数组中,而另一部分没有写入 struct 体的数组中.我的代码也奇怪地从第2931行读取数据,而不是从头开始.
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char location[100];
char city[100];
int price;
int room;
int bathroom;
int carpark;
char type[100];
char furnish[100];
} data;
int main() {
data house[4000];
FILE *file = fopen("data.csv", "r");
char buffer[1000];
fgets(buffer, 1000, file);
int n = 0;
while (fgets(buffer, 1000, file)) {
char *token = strtok(buffer, ",");
strcpy(house[n].location, token);
token = strtok(NULL, ",");
strcpy(house[n].city, token);
token = strtok(NULL, ",");
house[n].price = atoi(token);
token = strtok(NULL, ",");
house[n].room = atoi(token);
token = strtok(NULL, ",");
house[n].bathroom = atoi(token);
token = strtok(NULL, ",");
house[n].carpark = atoi(token);
token = strtok(NULL, ",");
strcpy(house[n].type, token);
token = strtok(NULL, "\n");
strcpy(house[n].furnish, token);
n++;
}
fclose(file);
for (int i = 0; i < n; i++) {
printf("%s,%s,%d,%d,%d,%d,%s,%s\n",
house[i].location, house[i].city, house[i].price,
house[i].room, house[i].bathroom, house[i].carpark,
house[i].type, house[i].furnish);
}
return 0;
}
这是data.csv的链接,我的程序从实际的3940个数据中读取了大约This is the image of comparison.0个数据.This is the image of comparison.
This is from the terminal, which shown the data from line 2931, not from the beginning.个
我想我必须提到这一点:在成功读取数据后,我想要做的是创建一个包含like this个菜单的菜单.所以程序可以做一些事情,比如显示数据,搜索数据,排序数据,并在排序后导出数据.在我的代码中使用这样的 struct 数组来完成我提到的所有任务是否已经正确?或者我可以换成更有效、更高效的东西?