读取CSV并在C中存储两个双数组

时间:2016-03-20 10:08:57

标签: c arrays csv

我想读一个包含数据点,即X和Y位置的csv文件。因此,我想读取CSV文件并将其存储在两个数组X和Y中。

我正在尝试以下代码:

#include <stdio.h>
#include <stdlib.h>

void readEntireFile(void);

int main(void) {

    readEntireFile();

    return EXIT_SUCCESS;
}

void readEntireFile(){
    int ch;
    FILE *fp;  // pointer to a file type
    fp = fopen("/geometrydata.csv", "r"); 
    ch = getc(fp);
    while (ch != EOF){  // keep looping until End Of File
        putchar(ch);    // print the characters read
        ch = getc(fp);
    }
    fclose(fp);
}

使用此代码我将获取文件中的记录,但是我不知道如何将这些记录存储在数组中。

文件中的记录格式如下

-3.5,0.00E+00
-3.289729021,0.00E+00
-3.090472028,0.00E+00

所以我必须将X存储为

[-3.5 -3.289729021 -3.09.472028] 

和Y为

[0.00E+00 0.00E+00 0.00E+00]

1 个答案:

答案 0 :(得分:0)

对于格式化数据,我建议fscanf

double X[NO_OF_LINES], Y[NO_OF_LINES]; /* NO_OF_LINES refers to the no of lines in your csv file */
int i;
for(i = 0; i < NO_OF_LINES && fscanf(fp, "%lf,%lf", &X[i], &Y[i]) == 2; i++);

if(i != NO_OF_LINES)
    fprintf(stderr, "ERROR! %d lines could not be read, success in reading %d lines", NO_OF_LINES, i);

for(int j = 0; j < i; j++)
    printf("X[%d] = %f, Y[%d] = %f", j, X[j], j, Y[j]);