im trying to read a file has many lines but after reading it every time i tried to printf it, but it always print just the last line???/


f = fopen("text.txt","r"[IMG]http://www.free2code.net/plugins/forums/images/smilies/icon_wink.gif[/IMG];
if(!f)
return 1;
while(fgets(s,1000,f) != NULL)
sprintf(value,s);
fclose(f);
printf("%s",value);


Recommended Answers

All 8 Replies

while(fgets(s,1000,f) != NULL)
sprintf(value,s);
fclose(f);
printf("%s",value);

You're only executing this: sprintf(value,s); in your while loop. What you want to do is:

while(fgets(s,1000,f) != NULL) 
{
sprintf(value,"%s", s); 
printf("%s",value);
}

I fixed a typo in your sprintf too

ps. Take these broken wings .... ;)

commented: Rightly pointed that out ~~SunnyPalSingh +3

You're only executing this: sprintf(value,s); in your while loop. What you want to do is:

while(fgets(s,1000,f) != NULL) 
{
sprintf(value,"%s", s); 
printf("%s",value);
}

I fixed a typo in your sprintf too.

Regards Niek

ps. Take these broken wings .... ;)

Thank you man........

but why that was happening with me i cant got it, why just printing the last line ???????

but why that was happening with me i cant got it, why just printing the last line ???????

Nick replied to that. Read again

You're only executing this: sprintf(value,s); in your while loop. What you want to do is:

while(fgets(s,1000,f) != NULL) 
{
sprintf(value,"%s", s); 
printf("%s",value);
}

Let me clarify by these two examples:

//example 1 
int i = 0;
while (i<=10)
{
   i++;
   printf("%d\n", i);
}
//example 2
int i = 0;
while (i<=10)
   i++;
   printf("%d\n", i);

The first example will print 1 2 3 etc 10, the second will print 10. This is because in the first example I use while() {} (curly brackets) which means : "execute the part in curly brackets while my statement is true". If you don't use the curly brackets you're telling the compiler: "execute the first line after the while statement, while my statement is true".

im really appretiated your cooperation, but i can conclude that sprintf store one line each time .......!?!?

No, it depends on what your inputstring is:

char Input[] = "this is \n two lines";
char Ouput[40] ;
sprintf(Output, "%s", Input);
printf("%s", Output);

This will output:

this is
two lines

Thank you man ... i got it now.....

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.