c - 将文件中的数据读入C中的结构

标签 c struct

我正在尝试将 CSV 文件中的数据读入结构数组。该程序计算了它需要多少结构并为它们分配了足够的内存,但我试图将数据扫描到数组中的尝试没有正常工作。 这是代码:

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

typedef struct{
   char *date;
   double open;
   double high;
   double low;
   double close;
   double volume;
   double adjclose;
} DATA;
DATA *table, *highest_table;

int main(int argc, char *argv[]){
    int size_counter = 0;
    DATA *table = (DATA *)malloc(size_counter*sizeof(DATA));
    DATA *highest_table = (DATA *)malloc(sizeof(DATA));
    FILE *file_input;
    file_input = fopen(argv[1], "r");
    //This counts to see how many lines are in the file to dedicate enough memory
    char buffer;
    for(buffer = getc(file_input); buffer != EOF; buffer = getc(file_input)){
        if(buffer == '\n')
          size_counter++;
    }
    size_counter = size_counter - 1;
    //Inputting the data from line into a series of dynamically allocated structers
    for(int i = 0; i < size_counter; i++){
        fscanf(file_input, "%c %lf %lf %lf %lf %lf %lf", &table[i].date, &table[i].open, &table[i].high, &table[i].low, &table[i].close, &table[i].volume, &table[i].adjclose);
    }

    printf("Date: %c\n", table[0].date);
    printf("Open: %f\n", table[0].open);
    printf("High: %f\n", table[0].high);
    printf("Low: %f\n", table[0].low);
    printf("Close: %f\n", table[0].close);
    printf("Volume: %f\n", table[0].volume);
    printf("Adj. Close: %f\n", table[0].adjclose);

  return 0;
}

这是输入文件的一小部分。然而,第一行是完全无关紧要的,但它必须被忽略(不,我不能删除第一行,因为这是一个作业。)

Date,Open,High,Low,Close,Volume,Adj. Close
17-Mar-06,11294.94,11294.94,11253.23,11279.65,2549619968,11279.65
16-Mar-06,11210.97,11324.80,11176.07,11253.24,2292179968,11253.24
15-Mar-06,11149.76,11258.28,11097.23,11209.77,2292999936,11209.77

最佳答案

乍一看有几个问题:

  1. 计算文件大小的第一个循环将读取流置于文件末尾之后。使用rewindfseek 将其放回去。

  2. 您的数据以逗号分隔;您的 fscanf 调用正在使用空格。要么修复该格式,要么更好,使用 fgets 获取整行,然后使用 strtok 进行解析。

关于c - 将文件中的数据读入C中的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49481877/

相关文章:

c - 类型 'ssize_t' 无法解析 eclipse cdt

D&C 的 C 实现比矩阵乘法的 Naive 解决方案更快?

c - 在c中指针变量保存的地址上使用模数

c - 警告 : assignment makes pointer from integer without a cast

c - 如何释放 c 中动态分配的结构数组?

C fork和pipe按顺序打印pid

c++ - 左移带有可变误差

c++ - 在 C++ 中使用结构作为映射中的值

c - 结构和链表内存分配valgrind错误

c - 我们必须 malloc 一个结构吗?