Naggappan Ramukannan
Naggappan Ramukannan

Reputation: 2812

Why do I get a null character when I read a second line with fscanf?

I am trying to read first line of the file completely until \n and store it in a variable. Then I try to read the 2nd line of the file, but it's not giving the correct output. I am not sure what is happening. Is it reading a blank, or maybe is the file pointer moving after fscanf()?

abc.txt file contains :

>hello test file<br>
1

But the output (what I get in printf) is:

status:
>pwd :hello test file

So why is status missing here?

Here is my program :

#include <stdio.h>
#include <string.h>

int main()
{
  char status,pwd[30];
  FILE *fp;
  fp=fopen("abc.txt","r");
  if(fp == NULL)
    {
        printf("Cannot open file ");
        fclose(fp);
       return 0;
    }

  fscanf(fp,"%29[^\n]",pwd);  
  fscanf(fp,"%c",&status);

  fclose(fp);
  printf("\n Status : %c pwd: %s",status,pwd);
}

Upvotes: 0

Views: 1102

Answers (2)

teppic
teppic

Reputation: 8195

The first fscanf is putting the newline back, and so the second fscanf is just reading the newline, not the character you want. You can get around this by putting a space before the %c, e.g.

fscanf(fp," %c",&status);

Upvotes: 1

Mike
Mike

Reputation: 49363

here:

 fscanf(fp,"%29[^\n]",pwd);  

You're telling fscanf() to read up until it sees a newline, then to stop. Here:

 fscanf(fp,"%c",&status);

You're telling fscanf() to read the next character (which is the newline). Then here:

printf("\n Status : %c pwd: %s",status,pwd);

It prints the newline as a character (so you can't see it, it's just a blank line)

You need to consume that newline if you want to read it like this with fscanf().

One option would be to just do something like:

fscanf(fp,"%29[^\n]",pwd); 
fgetc(fp);
fscanf(fp,"%c",&status);

Another resolution would be to add a space before the %c to tell fscanf() to ignore white space characters:

fscanf(fp,"%29[^\n]",pwd); 
fscanf(fp," %c",&status);

Upvotes: 3

Related Questions