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
Free preview
Create a free account to keep watching
It takes a minute and costs nothing. Your free account unlocks all of Chapter 1 and 3 more lessons of Programming in C.
Lesson complete
Earn the 3 college credits for Programming in C
Enrolling adds a quiz after each lesson, the graded work and the official transcript. Recommended for credit by NCCRS.
Next lesson: File Stream Management: fopen() and fclose() →← Workshop: Functions with Pointer ParametersNext lesson: File Stream Management: fopen() and fclose() →
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.
Enroll now → Course details Download the syllabus All Computer Science courses Every course with PRO →
Compare: C vs C++
Why take it here
Why students take Programming in C with UPI Study
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.
Thomas Edison State UniversitySigned partner
University of the PeopleSigned partner
Charter Oak State CollegeSigned partner
Strayer UniversitySigned partner
Columbia Southern UniversitySigned partner
Indiana TechSigned partner
Penn StateWorks with NCCRS
Southern New Hampshire UniversityWorks with NCCRS
SUNYWorks with NCCRS
+many more cooperating universitiesFind my college →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?
Why should error messages go to stderr instead of stdout?
What is a FILE pointer in C?
Why does printf output sometimes go missing when a C program stops suddenly?
About the Programming in C course
How many college credits is Programming in C?
How much does Programming in C cost and what is included?
Which universities accept UPI Study credits?
How long does Programming in C take?
How are the exams done?
How do my credits reach my college?
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.
3 credits · NCCRSEnroll →