Ayse
Ayse

Reputation: 2754

fscanf() returns negative value

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");
int size = -1;
while (!feof(fp))
{
    fgetc(fp);
    size++;
}
char buff[1000];
sprintf(buff,"%i",size);
MessageBox(NULL,
           buff,
           "Size",
           MB_ICONINFORMATION);

if(size > 0)
{
    while (fscanf(fp, " %s %d", ip, &port) > 0)
    {
        MessageBox(NULL,"fscanf() Successful","SUCCESS!", MB_ICONINFORMATION);
    }
}

Upvotes: 2

Views: 1989

Answers (2)

alk
alk

Reputation: 70971

You might like to add this call

rewind(fp);

just before

while (fscanf(fp, " %s %d", ip, &port) > 0)
{

Also one should always check the result of system calls. In your case mainly whether fopen() really did return something different from NULL.

Addtionally the while(!feof(fp)) construct mostly likely wouldn't always behave as expected (Why is “while ( !feof (file) )” always wrong?). You'd be better off going the way proposed by WhozCraig in the comment(s) below.

Upvotes: 3

Philip
Philip

Reputation: 5917

You don't need to determine the file size in advance. Just fscanf() the file and check the return value:

int ret;

while ((ret = fscanf(fp, " %s %d", ip, &port)) == 2) {
    MessageBox(NULL,"fscanf() Successful","SUCCESS!", MB_ICONINFORMATION);
}

switch (ret) {
    case EOF:
        /* EOF or error, check errno */
        break;
    case 0:
    case 1:
        /* bogus file contents */
        break;
    default:
        fprintf(stderr, "Philip says this cannot happen, but it did.\n");
        exit(EXIT_FAILURE);
}

Also: always check the return value of function calls.

Upvotes: 2

Related Questions