Click here to Skip to main content
15,893,588 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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:
C#
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
Updated 1-Apr-13 22:50pm
v5

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
C++
if(size > 0)
{
    while (fscanf(fp, " %s %d", ip, &port) > 0)
    {
        MessageBox (NULL, "fscanf() Successful", "SUCCESS!",
            MB_ICONINFORMATION);
    }
}

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.
 
Share this answer
 
Comments
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.
[This post is not an answer and should be removed — SA]

Adding rewind(fp) just before fscanf() solved the problem :)
 
Share this answer
 
v2

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900