简体   繁体   中英

reading csv file in C

please help me! enter image description here

my text file is here. I want to read all of them but i can take half of it. I dont know why..

Can you check my code? thnx a lot.

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);

Your test is misparenthesized. It should read:

if ((fp = fopen("init.csv", "r")) == NULL)

The second call fp = fopen("init.cvs","r"); is redundant and should be removed.

Also fscanf() is not a very good tool to parse CSV files:

  • if the file contains quoted strings with commas, scanning for , may have incorrect behavior.
  • it cannot handle empty fields
  • parsing errors are very difficult to recover from.

Assuming the file has simple contents, you should parse the first line separately to handle the columns numbers and change the fscanf() for this way:

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"))){

Below Code block

if((fp = fopen("init.csv","r")==NULL)) {
}

is wrong as first fopen("init.csv","r")==NULL) evaluated & if file is present it gives 0 (comparison operator) & then fp = 0 evaluated which hopefully not your intention.

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 */

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM