Wokers
Wokers

Reputation: 117

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

Upvotes: 1

Views: 133

Answers (3)

Henno Brandsma
Henno Brandsma

Reputation: 2166

Your fopen line should read (look at the difference: first assignment, then the check for its result).

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

Upvotes: 0

chqrlie
chqrlie

Reputation: 144750

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

Upvotes: 2

Achal
Achal

Reputation: 11921

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

Upvotes: 0

Related Questions