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
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: Random Access File Operations in C →← Line-Based Text File I/ONext lesson: Random Access File Operations in C →
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.
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 Structured Text File I/O: fprintf() and fscanf()
How do you read a name and a number from a file with fscanf?
Why does fscanf stop reading at a bad line in a file?
What is the difference between fscanf and sscanf?
How do you read comma-separated values with fscanf 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 →