Click here to Skip to main content
13,044,428 members (132,592 online)
Rate this:
Please Sign up or sign in to vote.
See more:
I am using fscanf() function to read data line by line from a text file. It was functioning fine but suddenly I don't know what mistake I made and now the function returns a negative value. below is my code snippet:
   FILE *fp;
   char ip[16];
   int port;
   fp = fopen("ClientInformation.txt", "r"); //open the file
   //Finding the Size of the file
   int size = -1;
   fseek (fp, 0, SEEK_END);  
   size=ftell (fp);
   if(size > 0) //proceed only if the file is not empty
         while (fscanf(fp, " %s %d", ip, &port) > 0)
               //scanf() successful

[edit]fixed code block[/edit]
Posted 1-Apr-13 20:55pm
Updated 1-Apr-13 22:50pm
Rate this: bad
Please Sign up or sign in to vote.

Solution 2

This is a good example of how NOT to do things. It starts with a typo in the essential word in the title of your post. The code you presented here has no reasonable indenting. And foremost, you are demonstrating bad programming techniques. There are easier methods of finding the length of a file than doing a character-by-character loop over its contents. If you had used one of those, you wouldn't have run into your problem in the first place.

The code in
if(size > 0)
    while (fscanf(fp, " %s %d", ip, &port) > 0)
        MessageBox (NULL, "fscanf() Successful", "SUCCESS!",

could be much simpler. The outer if-construct is totally useless. Your while loop will cover the case that the file is emply anyway. So, there is actually no need to determine the file length in the first step.

If it took you just 20 minutes to find the problem in your code, why did you post the question at all? I would have expected that you took so much thought before even posting a question.
ayesha hassan 2-Apr-13 4:38am
I know its all my mistake posting a stupid question + the typo.
I am really sorry :(
ayesha hassan 2-Apr-13 4:44am
Updated my question for you :)
nv3 2-Apr-13 4:49am
That looks a lot better now. You still can do away with the finding of the file length. You actually don't need it.
Rate this: bad
Please Sign up or sign in to vote.

Solution 1

[This post is not an answer and should be removed — SA]

Adding rewind(fp) just before fscanf() solved the problem :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Mobile
Web02 | 2.8.170713.1 | Last Updated 20 Apr 2013
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100