c語言讀取csv檔案
阿新 • • 發佈:2018-12-30
{
FILE*fp;floatvalue; system_time_t system_time;
charline[MAX_LINE];if((fp=fopen("d:\\1.csv","r"))==NULL) {
printf("Can't open d:\\1.csv\n"); }
memset(&system_time,0,sizeof(system_time_t));while(fgets(line, MAX_LINE, fp)) {
sscanf(line,"%f , %s%s%s%s%s",&value, system_time.week,system_time.month, system_time.date, system_time.hour_minute_second,system_time.year);
printf("value=%f system_time=%s %s %s %s%s\n", value, system_time.week,system_time.month, system_time.date,
system_time.hour_minute_second,system_time.year);
}
}
struct record_t
{
double money;
time_t tim;
};
typedef struct record_t record;
static const char *const short_months[12] = {
"Jan", "Feb", "Mar","Apr", "May", "Jun",
"Jul", "Aug", "Sep","Oct", "Nov", "Dec"
};
//把每行轉成record的資料結構。
record covert(char* inputval)
{
record retval;
char* comapos;
char weekday[4] = {'\0'}, mon[4]={'\0'};
struct tm gtm;
int n;
assert(inputval != null);
comapos = strstr(inputval, ",");
assert(comapos != null);
*comapos = '\0';;
retval.money = atof(inputval);
sscanf(comapos+1, "%s %s %d %d:%d:%d %d",weekday, mon, gmt.tm_mday, gmt.tm_hour, gmt.tm_min, gmt.tm_sec
gmt.tm_year);
for (n=0; n <12; n++)
if (strcmp(mon, short_months[n]) == 0)
break;
gmt.tm_mday = n;
gmt.tm_year -= 1900;
gmt.tm_isdst = -1;
retval.tim = mktime(&gmt) + GMTOFF(gmt);
return retval;
}
其他的很簡單了,從中間讀一行,判斷和你要的時間的大小,大則讀後面的中間一行,小則讀前面的一半的一行,通過遞迴讀出最你需要的那一行。
FILE*fp;floatvalue; system_time_t system_time;
charline[MAX_LINE];if((fp=fopen("d:\\1.csv","r"))==NULL) {
printf("Can't open d:\\1.csv\n"); }
memset(&system_time,0,sizeof(system_time_t));while(fgets(line, MAX_LINE, fp)) {
sscanf(line,"%f , %s%s%s%s%s",&value, system_time.week,system_time.month, system_time.date,
printf("value=%f system_time=%s %s %s %s%s\n", value, system_time.week,system_time.month, system_time.date,
system_time.hour_minute_second,system_time.year);
}
}
struct record_t
{
double money;
time_t tim;
};
typedef struct record_t record;
static const char *const short_months[12] = {
"Jan", "Feb", "Mar","Apr", "May", "Jun",
"Jul", "Aug", "Sep","Oct", "Nov", "Dec"
};
//把每行轉成record的資料結構。
record covert(char* inputval)
{
record retval;
char* comapos;
char weekday[4] = {'\0'}, mon[4]={'\0'};
struct tm gtm;
int n;
assert(inputval != null);
comapos = strstr(inputval, ",");
assert(comapos != null);
*comapos = '\0';;
retval.money = atof(inputval);
sscanf(comapos+1, "%s %s %d %d:%d:%d %d",weekday, mon, gmt.tm_mday, gmt.tm_hour, gmt.tm_min, gmt.tm_sec
gmt.tm_year);
for (n=0; n <12; n++)
if (strcmp(mon, short_months[n]) == 0)
break;
gmt.tm_mday = n;
gmt.tm_year -= 1900;
gmt.tm_isdst = -1;
retval.tim = mktime(&gmt) + GMTOFF(gmt);
return retval;
}
其他的很簡單了,從中間讀一行,判斷和你要的時間的大小,大則讀後面的中間一行,小則讀前面的一半的一行,通過遞迴讀出最你需要的那一行。