Can anyone explain in simple English about the differences between printf
, fprintf
, and sprintf
with examples?
What stream is it in?
I'm really confused between the three of these while reading about "File Handling in C".
cioprintfstream
Can anyone explain in simple English about the differences between printf
, fprintf
, and sprintf
with examples?
What stream is it in?
I'm really confused between the three of these while reading about "File Handling in C".
Best Answer
In C, a "stream" is an abstraction; from the program's perspective it is simply a producer (input stream) or consumer (output stream) of bytes. It can correspond to a file on disk, to a pipe, to your terminal, or to some other device such as a printer or tty. The
FILE
type contains information about the stream. Normally, you don't mess with aFILE
object's contents directly, you just pass a pointer to it to the various I/O routines.There are three standard streams:
stdin
is a pointer to the standard input stream,stdout
is a pointer to the standard output stream, andstderr
is a pointer to the standard error output stream. In an interactive session, the three usually refer to your console, although you can redirect them to point to other files or devices:In this example,
stdin
now points toinputfile.dat
,stdout
points tooutput.txt
, andstderr
points toerrors.txt
.fprintf
writes formatted text to the output stream you specify.printf
is equivalent to writingfprintf(stdout, ...)
and writes formatted text to wherever the standard output stream is currently pointing.sprintf
writes formatted text to an array ofchar
, as opposed to a stream.