How it works?

M

Mohan

Hi Friends,
The following code is working fine and printing the string "Mohan S".

#include<stdio.h>
int main()
{
FILE *fp;
fp=stdout;
fprintf(fp,"%s","Mohan S");
}

My doubt is how it is possible to assign a standard output stream to a
file stream....Why it didn't throw any error;instead its running
fine...

Can anyone give me clear explanations... ?
Thanks in advance...
Mohan Shanmugam
 
M

Mike Wahler

Mohan said:
Hi Friends,
The following code is working fine and printing the string "Mohan S".

#include<stdio.h>
int main()
{
FILE *fp;
fp=stdout;
fprintf(fp,"%s","Mohan S");
}

My doubt is how it is possible to assign a standard output stream to a
file stream....

Because they have the same type. 'stdout' has
type 'FILE *'. 'stdout', 'stdin', and 'stderr'
*are* FILE* streams.
Why it didn't throw any error;

Why should it? What error do you expect?
instead its running
fine...

It should, except for one thing: The last character output
should be a '\n', or 'fflush()' should be called, or the
output isn't guaranteed to appear.
Can anyone give me clear explanations... ?

See above.

-Mike
 
K

Keith Thompson

Mike Wahler said:
Because they have the same type. 'stdout' has
type 'FILE *'. 'stdout', 'stdin', and 'stderr'
*are* FILE* streams.


Why should it? What error do you expect?


It should, except for one thing: The last character output
should be a '\n', or 'fflush()' should be called, or the
output isn't guaranteed to appear.

Even with fflush(), it's implementation-defined whether a stream (such
as stdout) is required to end in a newline.

It's very likely that the output will appear (though on many systems
it may be immediately overwritten), but it's not guaranteed. Just add
a '\n', and you'll be fine.
 
B

Barry Schwarz

Hi Friends,
The following code is working fine and printing the string "Mohan S".

#include<stdio.h>
int main()
{
FILE *fp;
fp=stdout;
fprintf(fp,"%s","Mohan S");
}

My doubt is how it is possible to assign a standard output stream to a
file stream....Why it didn't throw any error;instead its running
fine...

Can anyone give me clear explanations... ?
Thanks in advance...
stdout is a FILE* that is declared in stdio.h and defined and
initialized by the startup code that executes prior to main. fp is a
FILE* defined in your program. It is perfectly legal for two pointers
to point to the same object.



Remove del for email
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,183
Messages
2,570,965
Members
47,511
Latest member
svareza

Latest Threads

Top