Reputation: 117
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
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
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:
,
may have incorrect behavior.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
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