Structured Text File I/O: fprintf() and fscanf(), Explained

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

Structured Text File I/O: fprintf() and fscanf()

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

← Line-Based Text File I/ONext lesson: Random Access File Operations in C →

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

In this lesson

Saving and loading records in text files with fprintf, fscanf, and sscanf.

  • Write records to a text file with fprintf and a chosen separator
  • Read records back with fscanf and test its return value
  • Handle damaged lines by reading with fgets and parsing with sscanf
  • Read comma-separated values with a scan set such as %11[^,]

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

Opening Question

Records With a Name and a Number

A score board isn't just lines of text. Each line has two pieces: a name, and a number. Save them together, and later you must pull them apart again, as a word and as a number you can add up. And sooner or later, one line in the file will be broken. Your program needs a plan for that too.

Writing Records

Fprintf With a Separator

You know printf and its format codes, percent s and percent d. Fprintf is the same tool, aimed at a file. Priya keeps each player in two arrays, side by side. Names of i and scores of i describe the same player. These are called parallel arrays. Structures, which bundle a name and a score into one thing, come in chapter ten. For now, parallel arrays do the job. The loop writes one record per line: the name, a space, the score, and a newline. Build and run it, then print the file. Three records, exactly in that shape. That space is the separator the reader will need later. Pick one that can't appear inside a field. These names have no spaces, so a space works.

Reading Records

Fscanf and Its Return Value

Now read that file back. Fscanf is scanf for a file: first the stream, then a format, then the places to store each piece. Percent eleven s reads one word, and stops at the first space. The eleven is a safety limit: name holds twelve characters, and one is kept for the null. Percent d reads a whole number. Score needs the ampersand, but name doesn't, because an array's name already stands for its address. Spaces and line breaks before a piece are skipped, so fscanf flows from one line to the next. The most important part is the return value: how many pieces fscanf stored. Equals two means: keep going while both pieces arrived. Build and run it. Two, two, two, one for each record. Then nothing more can be read, so fscanf returns E O F, a negative number. On this Mac, minus one. Minus one isn't two, so the loop ends.

Common Mistakes

Missing Ampersands and Percent Lf

Forget the ampersand, and fscanf would store the number at an address it was never given. Running that is undefined, and can crash. Luckily, clang checks scanf formats. Delete the ampersand and build: a warning. Percent d needs a pointer to int, and score is a plain int. One more trap: to read a double, fscanf needs percent l f. Printf uses percent f for both, but fscanf's percent f is only for float. Clang warns about that too.

Quick Check

Fscanf Reads Pieces, Not Lines

Quick check. Pairs dot text holds two players on its first line, Priya and Leo, and one more, Sam, on the second line. This loop counts the records fscanf reads, two pieces at a time. What does it print? Pause and predict. Three records. Fscanf doesn't care about lines. It skips any spaces or line breaks before each piece. So after Priya, forty-two hundred, the next word is Leo, on the same line. Then the line break is skipped on the way to Sam. Two would be right for fgets, which reads by lines. Fscanf reads by pieces.

Damaged Files

One Bad Record Stops the Loop

Real files get damaged: a typo, a half-saved line, letters where a number should be. Sam's test file, roster dot text, has one bad record. Line three says Sam, then abc. Here's the same kind of loop, pointed at it. Run it. It stopped quietly after two records. Fscanf read the word Sam, one piece, then failed to read a number from abc. It returned one, not two. Worse, abc is still unread in the stream, so asking for a number again would fail on it every time. Maya and Zoe, who were fine, never got read. Half the board vanished, and nothing complained.

The Fix

Fgets First, Then Sscanf

The fix comes in two steps. First, fgets takes the whole line out of the file, so even a bad line is always used up. Then S S C A N F, the s is for string, does what fscanf does, but reads the text already in your array. If both pieces arrive, the record is kept. If not, the program reports the line, and simply moves on to the next one. Build and run it. Lines one and two are fine. Line three is skipped. Maya and Zoe are back. Four good records out of five lines. Read the line first, then pick it apart. A broken record gets reported, instead of stopping everything.

CSV Files

A Scan Set Stops at the Comma

Many programs, spreadsheets included, save records as C S V, short for comma-separated values. One record per line, with commas between the fields. Plain percent s won't work here. It reads up to a space, so it would swallow the comma, and the number too. Percent eleven, then a bracket, caret, comma, and closing bracket, means: read up to eleven characters, and stop at a comma. The comma after it must match a real comma in the file. And the space at the front skips the line break left by the previous record. Build and run it. Three names, three scores, and a total of twelve thousand three hundred. Write with percent s, comma, percent d, and read with this format. Keep the two near each other, so a change to one reminds you of the other.

Key Takeaways

Write, Read, Validate, and Parse

To recap. Fprintf writes a record in the shape you choose, with a separator between the pieces. Fscanf reads it back, and returns how many pieces it stored. Loop while that's the number you asked for. For a file that may be damaged, take each line with fgets, then pick it apart with S S C A N F. And for C S V, a scan set like percent eleven, bracket, caret, comma, stops at the comma.

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 Structured Text File I/O: fprintf() and fscanf()

How do you read a name and a number from a file with fscanf?
Pass the stream, a format, and the places to store each piece: fscanf(f, "%11s %d", name, &score). %11s reads one word into a 12-element array, leaving room for the null terminator, and %d reads an integer. score needs the ampersand while name does not, because an array's name stands for its address. Loop while fscanf returns 2, the number of pieces you asked for.
Why does fscanf stop reading at a bad line in a file?
When fscanf cannot convert a piece, such as letters where %d expects a number, it returns fewer pieces than requested and leaves the bad text unread in the stream. A loop that continues only while the result is 2 then ends quietly, and every record after the bad one is skipped. Retrying would fail on the same text, so the robust fix is to read each line with fgets and parse it with sscanf.
What is the difference between fscanf and sscanf?
fscanf reads from a stream, such as a file, while sscanf reads from a string already in memory, using the same formats and the same kind of return value. A common pattern combines them: fgets takes a whole line out of the file, then sscanf(line, "%11s %d", name, &score) picks it apart. If it returns less than 2, the program reports that line and moves on, since the line is already used up.
How do you read comma-separated values with fscanf in C?
Use a scan set that stops at the comma, because %s reads up to whitespace and would swallow the comma and the number. The format " %11[^,],%d" skips leading whitespace, reads up to 11 non-comma characters into the name, matches the comma, and reads the integer. Write the file with a matching format, such as "%s,%d\n", and keep the two formats near each other.

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 →