UPI Study › Courses › Programming in C › Free lessons › Lesson 9.5 Free with a free account
File Stream Management: fopen() and fclose()
Programming in C · Chapter 9: String Manipulation via Pointers, File Streams, and File HandlingSection 9.5 · lesson 58 of 786 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: Line-Based Text File I/O →← The Stream I/O Model in CNext lesson: Line-Based Text File I/O →
In this lesson
Opening files with the right mode, checking for NULL, and closing them.
- Choose between the r, w, and a modes of fopen, with or without a plus
- Check fopen's return value for NULL and report the reason with perror
- Explain why mode w erases an existing file
- Explain what fflush and fclose do with buffered output
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 (906 words). Read along, or search it.
Opening Question
A Routine Like a Filing Cabinet
Picture a locked filing cabinet. You pick the right key, open the drawer, use the folder, and shut the drawer again. Skip a step, and something goes wrong: you read the wrong folder, throw away papers you needed, or leave the drawer hanging open. Files in C follow the same routine: fopen, check, use, and fclose. Today you learn each step, and what goes wrong without it.
File Modes
R Reads, W Starts Empty, A Appends
Fopen, short for file open, takes two strings: the file's name, and a mode. It returns the FILE star handle from lesson nine point four. The mode says what you plan to do, and it decides whether old data survives. Mode r reads. If the file is missing, fopen fails. If it exists, you start reading at the beginning. Mode w writes. A missing file is created. But an existing file is erased the moment it opens. Mode a appends. A missing file is created, and an existing file is kept, with new text added after the old. Add a plus, as in r plus, w plus or a plus, and you can go the other direction too. The rules about missing and existing files stay the same.
Checking for NULL
When Fopen Fails, Perror Says Why
Opening can fail, and not because of your code. The file might not exist, or the system might say you're not allowed. Then fopen returns NULL instead of a handle. Using a NULL handle is a crash waiting to happen. So the habit is: open, check, then use. Here, Priya tries to read a high-score file that hasn't been created yet. When the check finds NULL, perror, short for print error, prints our label, a colon, and the system's real reason. Build and run it. High scores dot text: no such file or directory. No crash, and no mystery. Perror writes to stderr, so the message stays out of the normal results. And main returns one, the usual signal that something went wrong. Ask the shell for the exit code, and there's the one. Now create the file, with one score in it, and run again. This time fopen returns a real handle.
Common Mistake
Mode W Erases the Old Board
Mode w is the one that bites. It doesn't mean write to the file. It means: give me a brand-new, empty file. Here's a board with three scores, made right in the terminal. Cat prints it back. This program opens board dot text with w, writes one line for Maya, and closes it. Build and run it, then print the file again. Three scores became one. No warning from C, and none from the compiler. The old lines were erased the moment fopen succeeded, before a single character was written. Now change the mode to a, and the line to Zoe's score. Build, run, and print the file. Maya's line survived, and Zoe's was added after it. So to add to a file, use a. To change it, read it first.
Quick Check
Append, Then Write, on One Log
Quick check. Log dot text holds three rounds. This program opens it with a, adds round four, and closes it. Then it opens the same file with w, writes round five, and closes it again. How many lines does log dot text hold at the end? Pause and predict. Just one line: round five. Append kept the three old rounds and added round four, so for a moment, there were four. But then mode w erased all four the moment it opened. Only round five was written after that. Five lines would be right only if the second open used a as well.
File Buffers
Fflush and What Fclose Returns
Files have a buffer too, like the screen's in lesson nine point four. Text you write with fprintf waits in memory, then goes to the disk in one trip. This program plays a second reader. The visible function opens the file, and counts the characters it can really find there right now. Fold it away. Main writes round one done, thirteen characters with the newline, and asks the reader after each step. Build and run it. After fprintf, the reader sees zero characters. The text is still waiting in the buffer. After fflush, all thirteen are there. Fflush sends the waiting text now. Fclose flushes whatever is left, then closes the stream. It returns zero on success. It returns something else if that last flush failed, on a full disk, for example. So the program checks it. And the file itself now holds the line.
Closing Files
Why Every Fopen Needs an Fclose
So when should you flush by hand? Rarely: for a log you want to read while the program is still running, or just before something risky. Otherwise, fclose does it for you. And fclose matters for a second reason. A program may keep only a limited number of files open at once. A handle you never close counts against that limit for as long as the program runs. Sam once tested the arcade's score saver by force-quitting it halfway through a session. The newest scores were missing from the file. Priya's program had written them with fprintf, but never closed the file. She added fclose at the end of each save, and Sam's next test lost nothing.
Key Takeaways
Open, Check, Use, Close
To recap. Pick the mode on purpose: r reads, w starts empty, and a adds at the end. A plus adds the other direction. Check what fopen returns for NULL, and let perror say why it failed. Never open a file you want to keep with w. And close every file you open: fclose flushes the buffer, and gives the handle back.
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 File Stream Management: fopen() and fclose()
What is the difference between the r, w, and a modes in fopen?
What does fopen return if a file cannot be opened in C?
Why did opening a file with mode w delete its contents?
Why is it important to call fclose in C?
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 →