Workshop: A Text File Processing Pipeline | Programming in C

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

Workshop: A Text File Processing Pipeline

Programming in C · Chapter 9: String Manipulation via Pointers, File Streams, and File HandlingSection 9.10 · lesson 63 of 786 min · free with a free account

← Binary File I/O: fread() and fwrite()Next lesson: Workshop: Saving and Restoring Structures in Binary Files →

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

In this lesson

Creating, appending, and updating fixed-width records in a text file.

  • Format fixed-width records with %-6s and %04d so every line is eleven bytes
  • Choose w, a, or r+ mode for creating, appending, or updating a file
  • Update one record in place with r+ and fseek without rewriting the file
  • Verify every file change by reading the file back and checking its size

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

The Challenge

Four Jobs for One Score File

The Starlight Arcade closes every night, and the high-score board must still be there in the morning. That takes a file and four jobs: build it, read it back, add a score at the end, and fix one score without touching the rest. And after every job, one rule: read the file back, and check what's really there.

Record Layout

Padding Every Line to Eleven Bytes

Every line of the board is exactly eleven bytes: a name padded to six characters, a score padded to four digits, and a newline. The format string does the padding. Percent minus six s is left-aligned, at least six wide. Percent zero four d is four digits, filled with zeros. With equal widths, record n starts at byte n times eleven. Record two, Leo's, starts at byte twenty-two.

Helper Functions

Three Helpers in One Header File

Priya keeps three helpers in one header file, board.h. RECLEN is eleven, the length of one record. create_board opens the file with w, which starts it empty. Then it writes four records, all with the same format. Two parallel arrays hold the data. The same index means the same player. print_board reads the file back with fgets, a line at a time, into twelve boxes: eleven bytes, plus the end marker. And board_size jumps to the end with fseek, then asks ftell where it is. That's the size in bytes.

Step One

Create the Board and Check Its Size

The first program only calls the helpers. The quotes in include board.h mean: look for the file next to this program. It creates the board, prints it back, and checks the size against a number worked out by hand: four times eleven. Build and run. Four records, Priya to Maya, and forty-four bytes, as expected. That hand-made number matters. A check that can only agree with itself proves nothing.

Step Two

Append Mode Adds a New Player

Now a new player, Nia, joins the board. Mode a, for append, adds every write after the last byte, and never erases anything. main builds a fresh board, then appends Nia. The same format string makes her record exactly eleven bytes. Build and run. Five records, and fifty-five bytes: forty-four, plus eleven.

Quick Check

Reading a Score at Byte 39

Quick check. The board from that last run is still on disk. This program jumps to record three, plus six bytes, and reads four characters. What does it print? Pause and predict. It prints byte 39: 0150. Records count from zero, so record three is Maya's. Three times eleven is thirty-three, and six more skips her name. fgets with five boxes reads four characters: her score. 0480 is Leo's score, in record two.

Step Three

Updating One Score in Place

Leo just beat his score, so record two must change, without rewriting the file. Mode w would erase the whole board when it opens. So the update uses r plus: read and write an existing file, and keep it. fseek to the record's start, plus the six name bytes: two times eleven, plus six, is byte 28. Then write exactly four digits. The function checks its inputs first. A score over 9999 would spill into the next record, and a record past the end would write beyond the file. Build and run. Leo now has 520, record nine is refused, and the size is still forty-four bytes. Nothing else moved. One more rule for r plus: on one stream, call fseek between reading and writing. C requires it.

Common Mistake

A Short Write Leaves a Stray Tail

Sam once tried a quick fix: percent s, space, percent d, with no fixed widths. It writes Sam 500 and a newline over record one. That's eight bytes, not eleven. Build and run. Five lines on a four-record board. The leftover tail, 75, became a record of its own. And the size is still forty-four bytes. Only a read-back reveals the damage.

Testing Habit

Four Jobs, Four Read-Backs

That's why Sam never trusts "it printed OK." After every change, he reads the file back and counts the bytes. Create with w: forty-four bytes. Append with a: fifty-five. Update with r plus: still forty-four. "Four jobs, four read-backs," he says.

Quick Check

Why Append Mode Ignores the Seek

Quick check. This program builds a fresh board, opens it with a, seeks to Sam's score, and writes 0300. After it runs, where did 0300 go? Pause and predict. On a new line at the end. Sam keeps 0275. In append mode, C sends every write to the end of the file, whatever fseek said. The board grew from 44 bytes to 49. So append can't damage a record, but it can't update one either. Updates need r plus. An emptied file would take w, which erases the board the moment it opens. And nothing fails here: the write simply goes to the end.

Key Takeaways

Choosing w, a, or r+ Correctly

To recap. Fixed-width records let you find record n at byte n times eleven. Create with w, append with a, and update in place with r plus and fseek. Every write keeps the same width, or the leftovers turn into records. And after every job, read the file 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 Workshop: A Text File Processing Pipeline

How do you make fixed-width records with fprintf in C?
Give every field a width in the format string so each line has the same length. For example, "%-6s%04d\n" left-aligns a name in at least 6 characters, prints the score as 4 digits padded with zeros, and adds a newline, for 11 bytes per record. Then record n starts at byte n times 11. A name longer than 6 characters or a score above 9999 would break the width, so check inputs first.
How do you update one record in a text file without rewriting it?
Open the file with mode "r+", which reads and writes an existing file without erasing it, then fseek to the exact byte and write the same number of bytes the field already uses. To change the score in record 2 of an 11-byte layout with a 6-byte name, seek to 2 times 11 plus 6, byte 28, and write exactly four digits. Mode "w" would empty the whole file.
Why does writing after fseek go to the end of a file in append mode?
In append mode, opened with "a", C sends every write to the end of the file, whatever position fseek set. So seeking to a score and writing 0300 simply adds 0300 at the end, and the original record keeps its old value. Append mode cannot damage an existing record, but it cannot update one either, so in-place updates need "r+" instead.
What happens if you overwrite a fixed-width record with a shorter line?
The leftover bytes of the old record stay in the file and become a stray line of their own. Writing Sam 500 plus a newline, 8 bytes, over the 11-byte record Sam 0275 leaves its last three bytes, 75 and a newline, behind. The file size does not change, so only reading the file back reveals the damage. Every write must keep the same width.

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 →