Jump to content
  • Advertisement
Sign in to follow this  
y2jsave

c file handling help

This topic is 3628 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

what is wrong in my code(which is in c) , it does not work it is for counting the numbers of lines in a text file char b[40]; int count=0; FILE *f=fopen(filename,"r"); if(f==NULL) printf("error in opening file"); while(!feof(f)) { fscanf(f,"%[^\n]s\n",&b); count++; } printf("%d",count);

Share this post


Link to post
Share on other sites
Advertisement
Quote:
Original post by nobodynews
This link suggests you should do this:

fscanf(f,”%[^\n]“,&b);


thanks , now it worked
but what was the mistake in the previous one?

Share this post


Link to post
Share on other sites
Quote:
Original post by y2jsave
Quote:
Original post by nobodynews
This link suggests you should do this:

fscanf(f,”%[^\n]“,&b);


thanks , now it worked
but what was the mistake in the previous one?


I have no idea, I just found that link which showed a different format than you had. You now know as much as I do!

Share this post


Link to post
Share on other sites
Another approach that's similar to your setup would be to use fgetc.

int c;
while(!feof(f))
{
c = fgetc(f);
if ( c == '\n' ) { count++; }
}

Share this post


Link to post
Share on other sites
Quote:
but what was the mistake in the previous one?
The mistake was to use logic based on feof. feof tells you if your previous i/o operation failed because of EOF (it could have failed for many reasons). The only way to know whether the next read will reach eof...is to actually try and read (think about this for a moment, how can feof know what lies ahead if it hasn't been read?).

If you want to count the number of lines, you could use logic based on repeatedly calling fgets. The various library functions do return a value, and it's in your best interest to figure out what they return, and make use of that return value.

Share this post


Link to post
Share on other sites
I may have actually figured out how that works. See here. It seems to be a MS specific way of doing things so that code might not be portable.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!