Line-Based Text File I/O, Explained with Code Examples

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

Line-Based Text File I/O

Programming in C · Chapter 9: String Manipulation via Pointers, File Streams, and File HandlingSection 9.6 · lesson 59 of 787 min · free with a free account

← File Stream Management: fopen() and fclose()Next lesson: Structured Text File I/O: fprintf() and fscanf() →

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

In this lesson

Reading and writing text files line by line with fgets and fputs.

  • Read a line from a file with fgets and explain its size limit
  • Remove the trailing newline from a line with strcspn
  • Loop over a whole file using the NULL return of fgets
  • Write lines with fputs and explain how it differs from puts

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,000 words). Read along, or search it.

Opening Question

Reading Text One Line at a Time

Most text in the world comes in lines: a list of names, a table of scores, a letter. Read a file one line at a time, and you can count the lines, search them, or sort them. C has a tool for exactly that. And it protects you from a nasty problem: a line that's longer than the space you set aside for it.

Meet Fgets

An Array, Its Size, and a Stream

Meet fgets. It takes three things: a character array to hold the text, the size of that array, and the stream to read from. The f is for file, and gets is short for get a string. The stream can be a file handle from nine point five, or stdin. Here's what it does, in order. It copies characters into your array, up to the end of the line. It keeps the newline that ended the line. It adds the null character at the end, so you hold a proper C string. And it never copies more than size minus one characters, so the array can't overflow.

The Data File

Newlines Are Real Characters

Here's the arcade's high-score file, scores dot text: six lines, with a name and a score on each. The newline at the end of each line is invisible here. Cat with dash e shows it: a dollar sign marks where each line ends. Those newlines are real characters in the file, and fgets will hand them to you.

Trimming the Newline

The Strcspn Trick

This program reads just the first line, prints it inside square brackets with its length, then removes the newline. Build and run it. Before: the closing bracket landed on the next line, because the newline is inside the text. The length is eleven: ten visible characters, plus the newline. The fix is line twelve. S T R C S P N, from string dot h, counts the characters before the first newline. That count is also the newline's index. Store the null character there, and the string ends just before it. After: length ten, and the bracket is back on the same line. If a line has no newline, the count is the whole length, and the trick changes nothing. So it's safe every time.

Long Lines

A Line Bigger Than the Array

What if a line is longer than the array? Make a file holding Starlight Arcade: fifteen letters and a space, then the newline. This program reads it into an array of only eight slots, and prints each piece in brackets. Build and run it. Fgets doesn't overflow. It stops early, and the rest of the line waits for the next call. With size eight, each call takes at most seven characters, because the eighth slot holds the null character. The newline arrives only with the last piece. That's how a program can tell the line is finished. So always pass sizeof line instead of typing a number, and make the array a little larger than your longest line. And never use the old gets function. It has no size at all, so it can't protect the array. C eleven removed it from the standard.

Reading to the End

Let Fgets Be the Loop Test

A file has some number of lines, and you rarely know it in advance. So keep calling fgets until it has nothing left to give. When there's no more text, fgets returns NULL instead of your array. That's how the program learns it reached the end of the file, often called E O F. Line twelve does two jobs at once: it reads the next line, and tests whether one came. Inside, the newline is trimmed and the line is counted. Build and run it. Six lines, and the program never needed to know six in advance. Now a classic mistake. Test feof before reading, and call fgets inside the loop. Run it. Line seven repeats Zoe! Feof becomes true only after a read has already failed. So the last fgets found nothing, left the old text in the array, and the loop counted it again. Let fgets itself be the test.

Quick Check

Leo's Line in an Array of Five

Quick check. Leo dot text holds one line: Leo, a space, thirty-one hundred, and the newline. This loop reads it into an array of five, and prints each piece in brackets. How many times does it print? Pause and predict. Three times. An array of five gives at most four characters a call: first Leo and the space, then thirty-one hundred. The newline is left over, so a third call delivers it alone. That's the bracket on the next line. Two would be right only if the newline weren't a character. Fgets counts it like any other.

Writing Lines

Fputs Adds No Newline

Writing is simpler. Fputs sends a string to a stream, and that's all. It doesn't add a newline, so put a backslash n in the text when you want one. The similar puts, which writes to the screen, does add one. That difference is a classic trap. This program writes on purpose in an odd way. Two fputs calls, for Maya, make a single line, because the first text has no newline. And Leo's last line has no newline at all. Then the file is read back with the loop you just learned. Build and run it. Maya's two pieces came back as one line. And the count is three, so a last line without a newline is still a line.

Quick Check

A Blank Line After Each Name

One more. Sam's file holds two players, Maya and Zoe, one per line. This loop prints every line with printf, percent s, backslash n, and trims nothing. What does the screen show? Pause and predict. A blank line after each name. Fgets kept each line's newline, and the format adds a second one. Sam saw exactly this gap under every name on the arcade's board. Priya added the S T R C S P N trim, and the gaps vanished.

Key Takeaways

Read, Trim, Loop, and Write

To recap. Fgets reads one line, keeps its newline, and never stores more than size minus one characters. Trim the newline with the S T R C S P N trick. Loop while fgets doesn't return NULL, not on feof. And fputs writes exactly what you give it, with no newline added.

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 Line-Based Text File I/O

How do you read a file line by line in C?
Call fgets in the loop test: while (fgets(line, sizeof line, f) != NULL) { ... }. Each call copies one line, including its newline, into line and adds the null terminator, storing at most sizeof line minus one characters. When no text is left, fgets returns NULL and the loop ends, so the program never needs to know the number of lines in advance.
Why does a while (!feof(f)) loop repeat the last line of a file?
feof becomes true only after a read has already failed, not before. In a loop that tests feof and then calls fgets, the final fgets finds nothing and returns NULL, leaving the previous text in the array, so the loop processes the last line a second time. Use the return value of fgets as the loop test instead.
What happens when a line is longer than the fgets buffer?
fgets stops early instead of overflowing, storing at most size minus one characters, and the rest of the line waits for the next call. With an 8-element array, each call takes at most 7 characters, so a long line arrives in pieces, and only the last piece contains the newline. Make the array larger than your longest line, and never use gets, which has no size limit and was removed in C11.
What is the difference between fputs and puts in C?
fputs writes a string to the stream you name, exactly as given, without adding a newline, so include \n yourself when you want one. puts writes to standard output and adds a newline after the string. Because fputs adds nothing, two fputs calls where the first text has no newline produce a single line in the file.

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 →