Click here to Skip to main content
11,806,818 members (58,173 online)
Rate this: bad
Please Sign up or sign in to vote.
See more: C Windows Win32 Text
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
Edited 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 at 2-Apr-13 4:38am
I know its all my mistake posting a stupid question + the typo.
I am really sorry :(
ayesha hassan at 2-Apr-13 4:44am
Updated my question for you :)
nv3 at 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 Smile | :)

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

  Print Answers RSS
0 ppolymorphe 245
1 OriginalGriff 150
2 George Jonsson 145
3 CPallini 100
4 Abhinav S 80
0 OriginalGriff 3,380
1 Maciej Los 1,990
2 CPallini 1,915
3 KrunalRohit 1,907
4 ppolymorphe 1,317

Advertise | Privacy | Mobile
Web03 | 2.8.151002.1 | Last Updated 20 Apr 2013
Copyright © CodeProject, 1999-2015
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