C/Problem with fgets and fscanf
Expert: Narendra - 9/5/2006
QuestionDear Narendra:
I got a problem trying to use fgets after fscanf. I don't know what the problem could be but I tried everything to meake it work. the fact is that fgets doen't read the line after using fscanf.I think I'm doing sthg wrong.I hope you can help me out before chewing my leg off. thanks in advance.
/*myprogram.c*/
#include <stdio.h>
#include <string.h>
int main()
{
char x[80] = " ITEM: TIMESTEP
" ;
char v[80];
FILE *file1;
int n;
if ( ( file1 = fopen( "history", "r" ) ) == NULL ) { printf("File history couldn't be opened
" );
return 0; }
printf ("Start
");
fgets(v,80,file1); /**it's ok**/
if (strcmp (v,x) == 0)
{printf ("%s
",v);}
fscanf(file1,"%d",&n); /********/
printf ("%d
",n);
fgets(v,80,file1); /*the problem*/
printf ("%s
",v); /*it prints nothing*/
printf ("End
");
fclose( file1 );
return 0;
}
history file.
*************************************************
ITEM: TIMESTEP
0
ITEM: NUMBER OF ATOMS
320
ITEM: BOX BOUNDS
68.399 68.399 68.399
ITEM: ATOMS
1 1 0.58547 0.73643 0.69263 0 0 0
2 1 0.58838 0.72944 0.69060 0 0 0
...
*************************************************
AnswerThe problem you are facing is because of the buffering involved in scanf() functions.
So, to overcome this, use fgets() in place of fscanf() and then use sscanf() to get the value.
Here is the modified code for you to try:
#include <stdio.h>
#include <string.h>
int main()
{
char x[80] = "ITEM: TIMESTEP" ;
char v[80] = "";
FILE *file1;
int n;
if ( ( file1 = fopen( "history", "r" ) ) == NULL )
{
printf("File history couldn't be opened " );
return 0;
}
printf ("Start ");
fgets(v,80,file1); /**it's ok**/
v[strlen(v) - 1] = '\0';
if (strcmp (v,x) == 0)
printf ("%s ",v);
fgets(v,80,file1); /**it's ok**/
sscanf(v,"%d",&n); /********/
printf ("%d ",n);
fgets(v,80,file1); /*the problem*/
printf ("%s ",v); /*it prints nothing*/
printf ("End ");
fclose( file1 );
return 0;
}
> I hope you can help me out before chewing my leg off.
I didn't get what you meant by that!?