我正在尝试将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
答案 0 :(得分:2)
乍一看有几个问题:
计算文件大小的第一个循环将读取流定位到文件末尾。使用rewind
或fseek
将其恢复。
您的数据以逗号分隔;您的fscanf
来电正在使用空格。要么修复该格式,要么更好,使用fgets
获取整行,然后使用strtok
进行解析。