The Stream I/O Model in C, Explained with Code Examples

UPI Study › Courses › Programming in C › Free lessons › Lesson 9.4 Free with a free account

The Stream I/O Model in C

Programming in C · Chapter 9: String Manipulation via Pointers, File Streams, and File HandlingSection 9.4 · lesson 57 of 788 min · free with a free account

← Workshop: Functions with Pointer ParametersNext lesson: File Stream Management: fopen() and fclose() →

Earn 3 college credits for Programming in CRecommended for credit by NCCRS · Computer Science 240 · self-paced · one payment, lifetime access

In this lesson

Standard streams, redirection, FILE pointers, and output buffering in C.

  • Name the three standard streams and what each one is for
  • Use fprintf and fscanf with an explicit stream argument
  • Explain how redirection separates stdout from stderr
  • Explain output buffering and when fflush is needed

Free study notes

Get this lesson's notes by email

The key points and 4 practice questions with answers, in your inbox. One email, free.

One email. Unsubscribe in one click.

Transcript

Everything said in the video, section by section (1,081 words). Read along, or search it.

Opening Question

How Printf Text Reaches the Screen

Every time you called printf, your words appeared on the screen. But your program has no screen-drawing code at all. So how did the text get there? The answer is one small idea: C treats all reading and writing as data flowing through pipes. Learn the pipes once, and the keyboard, the screen, and a file on disk all start to look the same.

Standard Streams

Stdin, Stdout, and Stderr

A stream is a pipe that carries characters, one after another, between your program and somewhere else. Your program only ever touches the pipe. It never needs to know what sits at the far end. When a program starts, C opens three streams for you, before main even runs. Standard input, stdin, usually brings in what you type. Scanf reads from it. Standard output, stdout, usually shows on the screen. Printf writes to it. And standard error, stderr, also shows on the screen. But it's meant for warnings and error messages. Their names live in stdio.h, the header you've included since your first program. So you've been using streams all along.

Proof in Code

Fprintf and Fscanf Name the Stream

Here's the proof. Line six uses printf. Line seven says the same thing the long way, with fprintf. Fprintf means file printf. It works like printf, but its first argument names the stream to write to. Here, that's stdout. Input works the same way. Line ten calls fscanf on stdin, the long way to write a plain scanf. Build it, run it, and type seven. Tokens five prints twice, because lines six and seven do exactly the same job. Then fscanf reads the seven, just as scanf would.

Two Output Streams

Results to Stdout, Complaints to Stderr

Why two output streams for one screen? Think of a school with two bells: one for class changes, and one for a fire drill. Stdout is for your program's real results. Stderr is for messages about the program: warnings and failures. Priya's program saves the arcade's score board. Two lines of results go to stdout, and one warning goes to stderr. Run it, and all three lines land on the screen, because both pipes end at the same place. The pipes only differ when you redirect one. Redirection tells the terminal to send a stream somewhere else. Two, then a greater-than sign, aims stream number two, stderr, at a file. Now the screen shows only the results. And the file holds the warning. Priya's rule of thumb: results go to stdout, complaints go to stderr. That way, when the results are saved to a file, no warning gets mixed into the data.

Quick Check

Redirecting Only Stdout to a File

Quick check. This loop sends fine scores to stdout, and a bad score to stderr. A plain greater-than sign, with no number in front, redirects stream one, stdout. Sam runs it with greater-than log dot text. What appears on the screen? Pause and predict. Only bad, minus five. The greater-than sign aimed stdout at the file, so both fine scores went into log dot text. Stderr was left alone, so the warning still reached the screen. That's the point of a separate pipe. Print the file, and there are the two results, with no warning mixed in. All three lines would show only with no redirection at all, and nothing at all only if both streams were redirected.

File Handles

FILE Star Is a Coat-Check Ticket

The three standard streams come ready-made. For any other stream, like a file on disk, you make one yourself. C then hands back a handle: a small token that stands for the open stream, like a coat-check ticket at a theater. You don't carry the coat around. You carry the ticket, and show it every time you want the coat. In C, the ticket has the type FILE star, said file pointer. FILE is defined in stdio.h, and you never look inside it. And here's the neat part: stdin, stdout and stderr are themselves FILE star values.

Worked Example

One Function, Any Destination

Here's one function that can write to the screen or to a file. Report takes a FILE star parameter called out, and writes to it with fprintf. In main, the first call passes stdout, so Priya's line goes to the screen. Then fopen makes a brand-new stream aimed at a file called board dot text, and returns its handle. Lesson nine point five covers fopen properly. The same report function now gets the board handle. And fclose hands the handle back when we're done. Build and run it. Only Priya's line shows. Leo's line went down the other pipe. Print the file with cat, and there it is: Leo scored thirty-one hundred. Report neither knows nor cares where its text ends up. The handle decides. A week later, the arcade's owner wanted a printed copy of the scores too. Priya changed nothing inside report. She just passed it a new handle.

Buffering

Output Waits Until a Flush

One more idea makes streams fast. Walking to the mailbox for every single letter would be slow, so you wait until you have a pile. C does the same with output. Characters wait in an area of memory called a buffer, then go out together. Sending the pile is called a flush. On this Mac, as on most systems, stdout aimed at a terminal flushes at each newline. A file's buffer flushes when it fills up, or when the file is closed. Calling fflush on a stream flushes it right now. And stderr has no buffer at all: its text goes out at once.

Common Trap

Unflushed Text Lost When the Program Stops

Most of the time, you never notice the buffer. But here's a moment where it matters. This program prints Step 1 done, with no newline. Then it sends a failure message to stderr. Then underscore Exit, from stdlib.h, stops the program on the spot, with no clean-up, much like a crash. Run it. Only Step 2 failed appears. Step 1 done was still waiting in the buffer when the program stopped, so it was lost. The C standard lets each system decide whether underscore Exit flushes. On this Mac, it doesn't. The fix is a newline at the end of the text. Build, run, and both lines appear. So end debug messages with a newline, or send them to stderr. And when a prompt has no newline, fflush of stdout pushes it out at once.

Key Takeaways

Streams, Handles, and Buffers

To recap. Every program starts with three streams: stdin brings data in, while stdout and stderr carry it out. Fprintf and fscanf name their stream as the first argument. Two, greater-than, redirects only stderr, so results and complaints stay apart. A FILE star is a handle for one open stream. And output waits in a buffer until a flush sends it.

About Programming in C at UPI Study

Programming in C (Computer Science 240) is a self-paced online course of 78 video lessons in 11 chapters, from pseudocode and your first program to data types, decisions, loops, functions, arrays, strings, pointers, files, structures, dynamic memory and linked lists. It carries a NCCRS credit recommendation for 3 semester credits.

Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Compare: C vs C++

Why take it here

Why students take Programming in C with UPI Study

How programs work close to the machineProgramming in C teaches how a program uses memory: variables and data types, control flow, functions, arrays and strings, pointers, files, structures and dynamic memory. C is the base for operating systems, embedded devices and many computer-science courses.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Where the credit goes

Universities that work with NCCRS

Programming in C carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.

FAQ

Questions students ask us

About The Stream I/O Model in C

What are stdin, stdout, and stderr in C?
They are the three standard streams C opens before main runs. stdin usually brings in what the user types, and scanf reads from it; stdout usually goes to the screen, and printf writes to it; stderr also goes to the screen but is meant for warnings and error messages. All three are declared in stdio.h with the type FILE *, so any function that takes a stream accepts them.
Why should error messages go to stderr instead of stdout?
Sending errors to stderr keeps them out of the program's real results. Both streams normally appear on the screen, but redirection can separate them: running a program with > results.txt sends only stdout to the file, so warnings still reach the screen, while 2> errors.txt sends only stderr to a file. That way, saved results never have a warning mixed into the data.
What is a FILE pointer in C?
A FILE * is a handle that stands for one open stream, like a coat-check ticket that stands for your coat. FILE is defined in stdio.h, and you never look inside it; you pass the handle to functions such as fprintf. fopen returns a new handle for a file, and stdin, stdout, and stderr are themselves FILE * values, so one function with a FILE * parameter can write to the screen or to a file.
Why does printf output sometimes go missing when a C program stops suddenly?
The text was probably still waiting in stdout's buffer. Output is collected in memory and sent in batches: stdout connected to a terminal is usually flushed at each newline, while a file's buffer is flushed when it fills or the file is closed. If a program stops abruptly, waiting text can be lost. End messages with a newline, call fflush(stdout), or send debug messages to stderr, which is unbuffered.

About the Programming in C course

How many college credits is Programming in C?
Programming in C (Computer Science 240) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does Programming in C cost and what is included?
$250, paid once, with lifetime access: all 78 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does Programming in C take?
It is self-paced with no deadlines. The 78 lessons total about 9 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

Ready for the full course? Earn 3 credits in Programming in C.

78 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.

Programming in C
3 credits · NCCRS
Enroll →