c - 读取 CSV 并存储在 C 中的两个 double 组中

标签 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]

最佳答案

对于格式化数据,我推荐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]);

关于c - 读取 CSV 并存储在 C 中的两个 double 组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36112434/

相关文章:

c - 如何正确使用qsort()?

javascript - 使用 JavaScript 读取 *.csv 文件

c - 为什么不引发异常?如果枚举大小小于 100 字节

c - 使用显式 openMP 任务分析 OpenMP 程序

arrays - 如何在 swift 4.2 中选择多个数组元素?

python - 使用python实现异构csv的数据结构

python - 如何根据python中的Where函数获取两列值

c - 读取的文件和写入的文件不相同

c - 为什么 TCP 保活数据包不触发 I/O 事件?是不是因为没有payload或者sequence number比connection的sequence number小1

python - 如何让 Numpy 给出列表数组而不是元组?