将数据从CSV文件添加到Struct

时间:2018-08-22 05:18:00

标签: c csv struct

我想知道如何将从CSV文件中读取的数据添加到Struct中(Struct甚至是最好的选择吗?)。我的CSV文件只有一个标头(x,y,u,v)下的4个值。计划是存储数据(不包含标题),然后对其进行处理和/或执行计算。 该文件读起来很好,一旦打开,我就感到困惑。

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <sys/time.h>
#include <string.h>
#include "tasks.h"

typedef struct {
    float xvalue;
    float yvalue;
    float uvalue;
    float vvalue;
} flow_data;

int main(int argc, char *argv[]) {

char* flow_file = NULL;
int resolution = 0;

flow_file = argv[2];
resolution = atoi(argv[3]);

// Reading flow_data.csv
FILE* flow_fileopen = fopen(flow_file, "r");

// Checking if the file has been read succesfully
if( flow_fileopen == NULL)
{
    perror("Error opening file");
    exit(1);
}

// Wasn't sure how to find the entry count, so I manually set it for now.
int entry_count = 7;

flow_data *dataset = malloc(sizeof(flow_fileopen) * entry_count);

char c;

do {
    c = fgetc(flow_fileopen);
    printf("%c", c );
} while (c != EOF);

free(dataset);

数据集是什么样

x y u v
1 2 3 4
2 3 4 5

1 个答案:

答案 0 :(得分:2)

flow_data *dataset = malloc(sizeof(flow_fileopen) * entry_count);

flow_fileopen是一个指针,sizeof(flow_fileopen)只是指针的大小(例如4或8)。您需要sizeof(flow_data)。您还可以使用sizeof(*dataset),它可能不太容易输入错误。

一旦分配了足够的内存,就可以使用fscanf来读取每一行,并将其保存到结构中。如果fscanf成功,则返回它读取的字段数。确保跳过包含字段名称“ x y u v”的第一行。

int entry_count = 7;
flow_data* dataset = malloc(sizeof(*dataset) * entry_count);

//skip the first line which includes field names
char buf[500];
fgets(buf, sizeof(buf), flow_fileopen);

int total = 0;
while(1)
{
    flow_data* p = &dataset[total];
    if(4 != fscanf(flow_fileopen, "%f %f %f %f\n",
        &p->xvalue, &p->yvalue, &p->uvalue, &p->vvalue))
    break;
    total++;
    if(total == entry_count)
        break; //this array can only hold a maximum of `entry_count`
}

不用猜测文件中有多少行,而是使用realloc根据需要增加数组的大小。

int main() 
{
    FILE* fp = fopen("flow_data.csv", "r");
    if(fp == NULL)
    {
        perror("Error opening file");
        exit(1);
    }

    char buf[500];
    fgets(buf, sizeof(buf), fp); //skip the first line

    int total = 0;
    flow_data d;
    flow_data* dataset = NULL;
    while(4 == fscanf(fp, "%f %f %f %f\n", &d.xvalue, &d.yvalue, &d.uvalue, &d.vvalue))
    {
        dataset = realloc(dataset, sizeof(*dataset) * (total + 1));
        dataset[total] = d;
        total++;
    }

    for(int i = 0; i < total; i++)
    {
        flow_data* p = &dataset[i];
        printf("%.1f, %.1f, %.1f, %.1f\n", p->xvalue, p->yvalue, p->vvalue, p->uvalue);
    }

    free(dataset);
    return 0;
}