File Stream Management: fopen() and fclose(), Explained

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

← The Stream I/O Model in CNext lesson: Line-Based Text File I/O →

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

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.

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 File Stream Management: fopen() and fclose()

What is the difference between the r, w, and a modes in fopen?
Mode "r" opens a file for reading and fails if it does not exist. Mode "w" opens for writing, creating a missing file but erasing an existing one the moment it opens. Mode "a" appends, creating a missing file and keeping an existing one, with new text added after the old. Adding a plus, as in "r+", "w+", or "a+", allows both reading and writing, with the same rules about missing and existing files.
What does fopen return if a file cannot be opened in C?
fopen returns NULL when it cannot open the file, for example because the file does not exist or permission is denied. Using a NULL handle can crash the program, so check right after opening: if (f == NULL) { perror("high_scores.txt"); return 1; }. perror writes your label, a colon, and the system's reason, such as No such file or directory, to stderr, and returning 1 signals failure.
Why did opening a file with mode w delete its contents?
Mode "w" means start with a brand-new, empty file, so an existing file is erased as soon as fopen succeeds, before a single character is written. Neither C nor the compiler warns about it. To add lines to an existing file, open it with "a" instead. To change data already in the file, read it first, then write out the updated version.
Why is it important to call fclose in C?
fclose flushes any text still waiting in the stream's buffer to the file and then releases the handle. Text written with fprintf may sit in memory until a flush, so a program that stops without closing can lose its newest output. A program can also keep only a limited number of files open at once. fclose returns 0 on success, so checking it catches a failed final write, such as on a full disk.

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 →