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
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: Structured Text File I/O: fprintf() and fscanf() →← File Stream Management: fopen() and fclose()Next lesson: Structured Text File I/O: fprintf() and fscanf() →
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.
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 Line-Based Text File I/O
How do you read a file line by line in C?
Why does a while (!feof(f)) loop repeat the last line of a file?
What happens when a line is longer than the fgets buffer?
What is the difference between fputs and puts 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 →