[英]reading csv file in C
请帮我! 在此处输入图片说明
我的文本文件在这里。 我想读所有这些,但我可以拿一半。 我不知道为什么。
你可以检查我的密码吗? 非常感谢。
FILE *fp;
char temp[10][250];
int i,j;
if((fp=fopen("init.txt","r"))==NULL)
{
printf("Reading Error!!");
}
fscanf(fp,"%d\n%d,%d", &botanist->water_bootle_size, &forest->height, &forest->width);
printf("%d %d %d ",botanist->water_bootle_size, forest->height, forest->width);
for(i=0;i<forest->height;i++)
{
fgets(temp[i],forest->width*2+1,fp);
}
for(int j=0;j<10;j++)
{
printf("%s",temp[j]);
}
fclose(fp);
您的测试是错误的。 它应显示为:
if ((fp = fopen("init.csv", "r")) == NULL)
第二个调用fp = fopen("init.cvs","r");
是多余的,应将其删除。
同样, fscanf()
并不是解析CSV文件的很好工具:
,
可能有不正确的行为。 假设文件内容简单,则应分别解析第一行以处理列号,并以这种方式更改fscanf()
:
if (fscanf(fp,"%d,%d,%d,%49[^,],%49[^,],%49[^,],%49[^,],%49[^,],%49[^,],%49[^,],%49[^,],%49[^,],%49[^,]",
&water, &x, &y, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10) == 13) {
/* 13 fields correctly parsed */
}
您的fopen行应显示为(看一下区别:首先分配,然后检查其结果)。
if (NULL == (fp = fopen("init.csv","r"))){
下面的代码块
if((fp = fopen("init.csv","r")==NULL)) {
}
是错误的,因为首先评估fopen("init.csv","r")==NULL)
&如果存在文件,则给出0
(比较运算符),然后评估fp = 0
,希望这不是您的意图。
if( (fp = fopen("init.csv","r")) == NULL) {
fprintf(stderr," some messagee ");
return 0;
}
else {
printf("it works");
}
//fp = fopen("init.cvs","r"); /* why open again */
fscanf(); /* check the return value */
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.