[一] 基础篇
[二] 进阶篇——写入CSV
[三] 进阶篇——读取CSV
在基础篇中,仅仅是将数据读取出来然后输出,并未将其转换为相应的数据类型。对于整数,我们可以使用 atoi()
、atol()
、atoll()
函数分别将字符串转换为 int
、long
、long long
类型;对于浮点数,我们可以使用 atof()
函数将字符串转换为 double
类型;而对于字符串,我们只需要使用 strdup()
进行复制一下即可。
在同一个 CSV 中的数据是具有相关性的,因此最好的方式是将构建一个结构体,利用结构体的成员来记录CSV文件不同列的数据。例如 CSV 文件内容如下:
ID,Name,Points
1,qwe,1.1
2,asd,2.200000
可以用如下的结构体进行记录:
struct student {
int id;
char *name;
double point;
};
结合上一小节处理读取得到的数据,那么最后的代码如下:
// 3-1.c
#include
#include
#include
char* get_field(char *line, int num);
char* remove_quoted(char *str);
struct student {
int id;
char *name;
double point;
};
void print_student_info(struct student *stu);
int main()
{
FILE *fp = fopen("tmp.csv", "r");
if (fp == NULL) {
fprintf(stderr, "fopen() failed.\n");
exit(EXIT_FAILURE);
}
char row[80];
char *token;
fgets(row, 80, fp);
char *header_1 = get_field(strdup(row), 1);
char *header_2 = get_field(strdup(row), 2);
char *header_3 = get_field(strdup(row), 3);
printf("%s\t%s\t%s", header_1, header_2, header_3);
char *tmp;
struct student stu;
while (fgets(row, 80, fp) != NULL) {
tmp = get_field(strdup(row