2

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);
    }
}
Jonathan Potter
  • 36,172
  • 4
  • 64
  • 79
Ayse
  • 2,676
  • 10
  • 36
  • 61

2 Answers2

3

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.

Community
  • 1
  • 1
alk
  • 69,737
  • 10
  • 105
  • 255
  • 3
    Or better still, just throw out the first while and use fseek/ftell/fseek. A one-char-at-a-time fread seems a bit obtuse just to determine a file size =P – WhozCraig Apr 02 '13 at 06:47
  • Thanks a ot everyone :). Adding rewind(fp) solved the problem, but I am not still clear how did that happen. I am new in all this, please explain if you can. – Ayse Apr 02 '13 at 07:03
  • 1
    @AyeshaHassan: Regarding what `rewind()` does you might like to read here: http://msdn.microsoft.com/en-us/library/fes6c2yd(v=vs.110).aspx having understood this you perhaps see what made it necessary to call `rewind()`. – alk Apr 02 '13 at 07:45
2

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.

Philip
  • 5,795
  • 3
  • 33
  • 68