🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →fscanf Formatted File Input
Read numbers and words back from files with fscanf in C, handle damaged lines safely, then test yourself with a quiz and interview questions.
This is the closing lecture of the file input and output section in our free C programming course. fscanf in C is the mirror image of fprintf: it reads text from a file, splits it according to a format string and stores the pieces in your variables. Together with fprintf it forms a complete save-and-load pair for readable data files, a pattern used all the time in embedded C programming for settings, test vectors and measurement logs.
We will read back the readings.txt file from the previous lecture, break the data on purpose to see how fscanf fails, fix it with fgets and sscanf, and finish with a small sensor statistics lab. At the end of this free C tutorial page you will find a quiz and a set of interview questions on everything covered in lectures 13 to 17.
What You Will Learn
- The declaration of fscanf and what its return value really counts.
- The correct way to loop until end of file.
- How to protect string fields from overflow with a field width.
- What happens on bad data and how fgets plus sscanf solves it.
- A complete write-then-read lab computing minimum, maximum and average.
- Quiz and interview questions for the whole file-handling block.
Prerequisites
- Lecture 16 on fprintf, because we read the file it created.
- Lecture 15 on fgets and strcspn.
- scanf conversion specifiers and the address-of operator.
How fscanf in C Works
int fscanf(FILE *stream, const char *format, ...);
fscanf behaves like scanf but takes its characters from a file. White space in the format matches any amount of white space in the input. Conversions such as %d, %f and %s skip leading white space, read a token and store it through the pointer you supply. Every argument after the format must therefore be an address: &value for numbers, plain array name for strings.
The return value is a count
fscanf returns the number of items it successfully stored. If it reaches end of file before the first conversion it returns EOF. If it stops because the text does not match, it returns the count so far, which may be zero. That makes three different situations: success, clean end of file and bad data. Your loop must tell them apart.
Meaning of the fscanf return value for a format with 2 conversions
Reading the Records File Back
#include <stdio.h>
int main(void)
{
char tag[12];
float volts;
int rc;
FILE *fp = fopen("readings.txt", "r");
if (fp == NULL) {
perror("fopen");
return 1;
}
while ((rc = fscanf(fp, "%11s %f", tag, &volts)) == 2)
printf("%-5s -> %.2f V\n", tag, volts);
if (rc == EOF)
printf("clean end of file\n");
else
printf("stopped: bad data (rc=%d)\n", rc);
fclose(fp);
return 0;
}
$ gcc -Wall -Wextra -o ep_fscanf_records ep_fscanf_records.c
$ ./ep_fscanf_records
ADC0 -> 3.30 V
ADC1 -> 1.65 V
VBAT -> 4.02 V
clean end of file
Two details deserve attention. First, the loop condition compares the result with 2, the number of conversions, rather than with EOF. This one choice also catches malformed lines. Second, %11s limits the name to 11 characters, leaving room for the terminator in the 12-byte array. Without that number, a long word in the file would overflow tag.
Never write while (!feof(fp)) around fscanf. The end-of-file flag is set only after a read has already failed, so the loop runs once too often and processes stale values. Control the loop with the return value of fscanf instead.
When Data Is Damaged: fgets plus sscanf
Suppose the second line of the file contains the text “oops” instead of a number. A fscanf loop stops there with a return value of 1, and the remaining good line is never read. Worse, the unreadable characters stay in the stream, so calling fscanf again fails forever at the same place. For input you cannot fully trust, read one line with fgets, then parse that line with sscanf. A bad line affects only itself.
#include <stdio.h>
int main(void)
{
char line[64], tag[12];
float volts;
int lineno = 0;
FILE *fp = fopen("messy.txt", "r");
if (fp == NULL) {
perror("fopen");
return 1;
}
while (fgets(line, sizeof line, fp) != NULL) {
lineno++;
if (sscanf(line, "%11s %f", tag, &volts) == 2)
printf("line %d ok : %s %.2f\n", lineno, tag, volts);
else
printf("line %d skip: bad format\n", lineno);
}
fclose(fp);
return 0;
}
$ printf 'ADC0 3.30\nADC1 oops\nVBAT 4.02\n' > messy.txt
$ gcc -Wall -Wextra -o ep_fgets_sscanf ep_fgets_sscanf.c
$ ./ep_fgets_sscanf
line 1 ok : ADC0 3.30
line 2 skip: bad format
line 3 ok : VBAT 4.02
Two ways to read a text record file
Lab: Sensor Statistics From a Text File
This final lab ties lectures 15 to 17 together. The program creates a file of six temperature samples with fprintf, reads them back with fscanf and computes the number of samples, minimum, maximum and average. It also guards against an empty file, so there is no division by zero.
#include <stdio.h>
int main(void)
{
unsigned id, n = 0;
float t, sum = 0.0f, lo = 0.0f, hi = 0.0f;
float samples[] = { 24.5f, 25.1f, 23.8f, 26.4f, 25.0f, 24.2f };
FILE *fp = fopen("temps.txt", "w");
if (fp == NULL) {
perror("fopen");
return 1;
}
for (unsigned i = 0; i < 6; i++)
fprintf(fp, "%u %.1f\n", i + 1, samples[i]);
fclose(fp);
fp = fopen("temps.txt", "r");
if (fp == NULL) {
perror("fopen");
return 1;
}
while (fscanf(fp, "%u %f", &id, &t) == 2) {
if (n == 0 || t < lo) lo = t;
if (n == 0 || t > hi) hi = t;
sum += t;
n++;
}
fclose(fp);
if (n == 0) {
puts("no samples");
return 1;
}
printf("samples=%u min=%.1f max=%.1f avg=%.2f\n", n, lo, hi, sum / n);
return 0;
}
$ gcc -Wall -Wextra -o ep_sensor_stats ep_sensor_stats.c
$ ./ep_sensor_stats
samples=6 min=23.8 max=26.4 avg=24.83
$ cat temps.txt
1 24.5
2 25.1
3 23.8
4 26.4
5 25.0
6 24.2
Check the average by hand: 24.5 + 25.1 + 23.8 + 26.4 + 25.0 + 24.2 = 149.0, and 149.0 divided by 6 is 24.83. Try the lab yourself: add a seventh line to temps.txt by hand with the text “bad” and watch how the loop stops.
fscanf in Embedded C Programming
- Loading calibration constants and thresholds from a text file on embedded Linux.
- Replaying recorded sensor data into an algorithm on the host before flashing the target.
- Reading test vectors for unit tests of parsing and filtering code.
On a microcontroller, scanf-family functions pull in a lot of code, so firmware often parses simple fields with strtol and strtof instead. The habit of checking how many items were converted still applies.
Common Mistakes and Troubleshooting
| Mistake | Effect | Fix |
|---|---|---|
| Forgetting the & on a number | Crash or memory corruption | Pass &value for int, float and so on, not for char arrays |
| %s without a width | Buffer overflow on long words | Use %11s for a 12-byte array |
| while (!feof(fp)) | Last record processed twice | Loop on the fscanf return value |
| Comparing the result with EOF only | Infinite loop on bad data | Compare with the expected item count |
| Different format than fprintf used | Wrong values or early stop | Keep the write and read formats in step |
| %f stored into a double | Wrong numbers | Use %lf for double with scanf-family functions |
Best Practices, Performance and Security
- Always put a width on %s conversions. Treat an unbounded %s like gets.
- Trust nothing from files. Validate ranges after reading, for example reject negative sample counts.
- Choose fscanf for clean, machine-written files and fgets plus sscanf for files that humans edit.
- Check fopen, and report which file failed with perror.
- For large data sets, binary storage with fread is much faster than text parsing, at the cost of readability.
Key Takeaways and Conclusion
Summary
- fscanf returns the number of items stored, or EOF when input ends before the first conversion.
- Loop with == (number of conversions), not with feof.
- Use a width with %s and the address operator with numbers.
- fgets plus sscanf isolates damaged lines and keeps the rest of the file usable.
- fprintf and fscanf must use matching formats to round-trip data.
You have now completed the text file functions of this chapter: fputc and fgetc, putw and getw, fputs and fgets, fprintf and fscanf. These calls are the daily tools for every free embedded C course graduate who works with logs, settings and data files. Test yourself below, then move on to the next lecture in the course.
Quiz: Files and String I/O
Answer each question, then open the answer to check yourself.
-
A file contains the integers 5, -1, 9 written with putw. What does while ((v = getw(fp)) != EOF) print?
- A. 5 -1 9
- B. 5
- C. 5 -1
- D. Nothing
Show answer
B. The value -1 equals EOF, so the loop ends after printing 5.
-
fputs(“abc”, fp) writes how many bytes?
- A. 3
- B. 4
- C. 5
- D. It depends on the compiler
Show answer
A. Three characters, no null terminator and no newline.
-
fgets(buf, 8, fp) can store at most how many characters from the file, not counting the terminator?
- A. 8
- B. 7
- C. 9
- D. 1
Show answer
B. It stops after n-1 = 7 characters so that the null byte fits.
-
Which function adds a newline automatically?
- A. fputs
- B. fprintf
- C. puts
- D. fwrite
Show answer
C. puts writes the string to stdout and then a newline.
-
fscanf(fp, “%d %d”, &a, &b) reads the text “7 x”. What does it return?
- A. 2
- B. 1
- C. 0
- D. EOF
Show answer
B. It converted a = 7, then failed to match the second number.
-
Why is gets not used in modern C?
- A. It is too slow
- B. It cannot limit the input length
- C. It only works with files
- D. It adds a newline
Show answer
B. It can overflow the buffer, and it was removed in C11.
-
True or false: fprintf(stdout, “hi\n”) is equivalent to printf(“hi\n”).
Show answer
True. printf always writes to stdout.
-
A float is read with fscanf. Which specifier is right for a double variable?
- A. %f
- B. %d
- C. %lf
- D. %s
Show answer
C. In the scanf family, %lf stores into a double; %f stores into a float.
Interview Questions on C File Handling
1. Why can getw not be used safely to read integers in a loop?
getw signals end of file and errors with EOF, which is -1, a valid integer. A stored -1 ends the loop early. Safe code checks feof and ferror after a -1, or uses fread, whose return value is an item count.
2. What is the difference between puts and fputs?
puts writes to stdout and appends a newline. fputs writes to any stream and appends nothing.
3. Does fgets keep the newline? How do you remove it?
Yes, if the newline fits in the buffer. Remove it with buf[strcspn(buf, “\n”)] = ‘\0’.
4. How do you tell end of file from an error after fgets returns NULL?
Call feof(fp) for end of file and ferror(fp) for a read error.
5. Why is while (!feof(fp)) a bad loop condition?
The end-of-file indicator is set only after a read attempt fails, so the loop body runs once more with stale data. Test the return value of the read function instead.
6. How do you make fscanf safe for string input?
Add a maximum field width smaller than the array size by one, for example %11s for char tag[12].
7. When would you choose fgets plus sscanf over fscanf?
When the file may contain damaged or hand-edited lines. Parsing one line at a time lets you skip a bad line and continue.
8. What is the danger of fprintf(fp, user_string)?
If user_string contains % conversions, fprintf interprets them and reads arguments that do not exist, which can leak or corrupt memory. Use fprintf(fp, “%s”, user_string) or fputs.
9. Text file or binary file for storing sensor data? Explain the trade-off.
Text is readable and easy to debug but larger and slower to parse. Binary is compact and fast but depends on type sizes and byte order, so it needs fixed-width types and a documented layout.
10. What do fprintf and fscanf return?
fprintf returns the number of characters written, or a negative value on error. fscanf returns the number of items assigned, or EOF if input ended before the first conversion.
Frequently Asked Questions
What does fscanf return when it reaches the end of the file?
It returns EOF if no conversion succeeded before the end of input. Test for the expected item count to catch both end of file and bad data.
Why does my fscanf loop never end?
A bad token stays in the stream, so fscanf keeps failing at the same spot. Stop the loop when the return value differs from the item count, or use fgets plus sscanf.
Do I need the address-of operator with fscanf?
Yes for numbers and single characters. Array names used with %s already decay to addresses, so no ampersand is needed.
How do I read a name that contains spaces?
%s stops at white space. Use fgets for the full line, or the scan set %[^\n] with a field width.
Is fscanf slow?
It is fine for small and medium files. For very large data, read binary blocks with fread, which avoids text parsing.
Where can I follow more of this free C programming course?
Use the course index link on this page. Each lecture of the free C tutorial for embedded C programming has tested code and expected output.
Finished the File I/O Block
Great work. Continue this free embedded C course with the next file-handling lecture.

2 Comments