【发布时间】:2015-09-14 07:29:13
【问题描述】:
我需要从 CSV 文件中读取一些数据并创建一个数据结构,以便创建一个哈希表。我尝试了很多,浪费了很多时间,但没有结果。请检查我的代码并帮助我找出错误所在...
这是文件数据、输出和代码。
(我一个人写了代码,在Deitel的C编程语言和Deitel书的帮助下。)
代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
struct clientData
{
int acctNum;
char breaker[50];
char datetime[60];
double current;
};
int main()
{
FILE *cfPtr;
struct clientData client = {0,"","",0.0 };
if ( ( cfPtr = fopen("data1.csv","rb") ) == NULL)
{
printf("File could not be opened.\n");
}
else
{
printf("%-6s%-16s%-11s%10s\n","Acct","Last Name","First Name","Balance");
while ( !feof( cfPtr) )
{
fread( &client , sizeof ( struct clientData ), 1 , cfPtr );
if ( client.acctNum !=0 )
{
printf ("%-6d%-16s%-11s%10.2f\n",
client.acctNum,client.breaker,client.datetime,client.current );
}
}
fclose ( cfPtr );
}
return 0 ;
}
CSV 输入文件
acct,breaker,S_TimeStamp,MeasurementValue 1、EthiotideAtalantiMVBreakerBB2Q2Current,1/12/20158:30,37.6 2、EthiotideAtalantiMVBreakerBB2Q2Current,1/12/20159:00,34.2 3、EthiotideAtalantiMVBreakerBB2Q2Current,1/12/20159:30,37.2 4,EthiotideAtalantiMVBreakerBB2Q2Current,1/12/201510:00,40.6 5,EthiotideAtalantiMVBreakerBB2Q2Current,1/12/201510:30,41.8 6、Eth1iotideAtalantiMVBreakerBB2Q2Current,1/12/201511:00,45.8
输出
Acct 姓氏 名字 余额 1952670561,断路器,S_TimeStamp,MeasurementValue 1、EthiotideAtalantiMVBreakerBB2Q2Current,1/12/20158:30,37.6 2、EthiotideAtalantiMVBreak@talantiMVBreakerBB2Q2Current,1/12/20158:30,37.6 2,EthiotideAtalantiMVBreak @ 178724158464812467496986462827554460798109233540662154481413250685702096704425934569739618465990294960631478737616585889239313529311067888348744695823558167564353119398296863451093505908419875899425197001801728.00 11116509172Q2Current 1 /二万零一百五十九分之十二:00,34.2 3、EthiotideAtalantiMVBreakerBB2Q2Current,1/12/20159:30,37.2 4、EthiotideAtalantiMVBreakerBB2Q2C@VBreakerBB2Q2Current,1/12/20159:30,37.2 4、EthiotideAtalantiMVBreakerBB2Q2C@5155825882657381.00 1701999221nt,1/12/201510:00,40.6 5,EthiotideAtalantiMVBreakerBB2Q2Current,1/12/201510:30,41.8 6、Eth1iotideAtalantiMVBreakerBB2Q2Curren@rBB2Q2Current,1/12/201510:30,41.8 6,Eth1iotideAtalantiMVBreakerBB2Q2Curren @ 62020397019943253271215041932658580009235443368333447944639125867547040589859590642175830919754237423637956114804980964218473105282339526865630710982971497957257635386734871861549462238776468516448931338295812955819267325952.00201511分之79175179612:00,45.8 40.6 5,EthiotideAtalantiMVBreakerBB2Q2Current,1/12/201510:30,41.8 6,Eth1iotideAtalantiMVBreakerBB2Q2Curren@rBB2Q2Current,1/12/201510:30,41.8 6,Eth1iotideAtalantiMVBreakerBB2Q2Curren @ 62020397019943253271215041932658580009235443368333447944639125867547040589859590642175830919754237423637956114804980964218473105282339526865630710982971497957257635386734871861549462238776468516448931338295812955819267325952.00 P>
【问题讨论】:
-
CSV 仅为
chars s。您无法使用fread()直接从中读取任何其他内容。您需要解析文本 (chars) 读取并将结果转换为特定变量,如ints 和doubles 或使用fscanf()。
标签: c csv data-structures hash