🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →C File Handling Lab Quiz
Build an ADC data logger, then test yourself with a quiz and interview questions on files, streams, EOF and character I/O.
Theory sticks when you use it. This C file handling lab closes the first part of the Files chapter in our free C programming course. You will build a small ADC data logger that writes samples to a binary file, reads them back safely and prints statistics. Then you will test yourself with a ten-question quiz, three output and programming questions, and twelve interview questions on fclose(), EOF, the standard streams and character input and output.
The lab is written for embedded C programming: a fake 12-bit converter stands in for real hardware, so you can run it on any Linux machine today and later replace the sample source with a driver call. Everything in this lecture was compiled with gcc -Wall -Wextra and run.
What You Will Learn
In this free C tutorial you will:
- Complete a C file handling lab that uses open, check, write, read, close and error reporting together.
- Separate results (stdout) from diagnostics (stderr).
- Read integers back with a loop that does not trust the returned value.
- Revise six lectures with a summary table and a quiz.
- Answer common interview questions on C file handling.
Prerequisites
The previous lectures in this part: fclose(), EOF, the standard streams, fputc(), fgetc() and putw() with getw(). A Linux terminal with gcc is all the equipment you need.
C File Handling Lab: The ADC Logger Design
Requirements: generate 20 samples from a pretend 12-bit ADC, store them in a binary file called adc.bin, read the file back, and print the sample count, the minimum, the maximum and the average. Report problems on stderr and return a failure code to the shell.
Data flow of the lab
The design splits the work into two functions, log_samples() and analyse(). Each opens its own file handle, closes it before returning, and reports failure with a return value instead of calling exit(). That keeps the open-and-close pairs visible and makes each function easy to test alone.
C File Handling Lab: Complete Source Code
#include <stdio.h>
#include <stdlib.h>
#define SAMPLES 20
#define LOG_FILE "adc.bin"
/* Fake 12-bit ADC: a small linear congruential generator, deterministic. */
static unsigned adc_read(void)
{
static unsigned seed = 2024;
seed = seed * 1103515245u + 12345u;
return (seed >> 16) & 0x0FFF;
}
static int log_samples(const char *path)
{
FILE *fp = fopen(path, "wb");
if (fp == NULL) {
perror(path);
return -1;
}
for (int i = 0; i < SAMPLES; i++) {
if (putw((int)adc_read(), fp) == EOF && ferror(fp)) {
fprintf(stderr, "write failed at sample %d\n", i);
fclose(fp);
return -1;
}
}
return fclose(fp) == EOF ? -1 : 0;
}
static int analyse(const char *path)
{
FILE *fp = fopen(path, "rb");
if (fp == NULL) {
perror(path);
return -1;
}
int v, count = 0, min = 0, max = 0;
long sum = 0;
for (;;) {
v = getw(fp);
if (feof(fp) || ferror(fp))
break;
if (count == 0 || v < min) min = v;
if (count == 0 || v > max) max = v;
sum += v;
count++;
}
if (ferror(fp)) {
fprintf(stderr, "read error after %d samples\n", count);
fclose(fp);
return -1;
}
fclose(fp);
if (count == 0) {
fprintf(stderr, "no samples found in %s\n", path);
return -1;
}
printf("samples : %d\n", count);
printf("min : %d\n", min);
printf("max : %d\n", max);
printf("average : %ld\n", sum / count);
return 0;
}
int main(void)
{
if (log_samples(LOG_FILE) != 0)
return EXIT_FAILURE;
fprintf(stderr, "[info] %d samples written to %s\n", SAMPLES, LOG_FILE);
return analyse(LOG_FILE) == 0 ? EXIT_SUCCESS : EXIT_FAILURE;
}
Build and run
gcc -Wall -Wextra -o ep_adclog ep_adclog.c
./ep_adclog
echo "exit code: $?"
wc -c < adc.bin
[info] 20 samples written to adc.bin
samples : 20
min : 57
max : 3992
average : 2145
exit code: 0
80
The first line is the progress message on stderr. The four result lines come from stdout. The file holds 80 bytes, which is 20 integers of 4 bytes each. Run ./ep_adclog 2>/dev/null to see only the results, which shows why the two streams are kept apart. The generator is deterministic, so you should see exactly the same numbers.
Walking Through the Lab
| Part of the code | Concept from the lectures | Why it matters |
|---|---|---|
fopen() followed by a NULL check and perror() | Standard open, check | A missing directory or read-only medium gives a clear message |
putw(...) == EOF && ferror(fp) | Return value plus stream flag | A written value that equals -1 cannot be mistaken for failure |
return fclose(fp) == EOF ? -1 : 0; | Checked fclose() | Reports a flush failure such as a full file system |
v = getw(fp); if (feof(fp) || ferror(fp)) break; | EOF is a stream state | Reads every value, even -1 |
fprintf(stderr, ...) | Standard streams | Diagnostics never pollute the results |
return ... ? EXIT_SUCCESS : EXIT_FAILURE; | Exit status | Scripts and build systems can react |
Notice what the program does not do. It never uses fcloseall(), never loops on feof(), never stores a read result in a char, and never leaves a file open on an error path. Each earlier lecture contributed one of these decisions.
Extend the C File Handling Lab: Practice Exercises
- Replace
putw()andgetw()withfwrite()andfread()usinguint16_tsamples. Compare the file size. - Make the file name a command-line argument and print a usage message on stderr when it is missing.
- Detect a damaged file whose size is not a multiple of the sample size, and report it.
- Add a moving average of the last four samples and print it next to each sample.
- Write the samples as text, one per line, with
fputc()andfputs(), and read them back withfgets(). - Make the logger write to
/dev/fulland confirm that your error handling reports the failure.
Hint for exercise 6
Writes to /dev/full succeed in the buffer and fail on flush, exactly as in the fclose() lecture. If your program says everything is fine, you are not checking the result of fclose().
Revision Table for the Whole Part
| Lecture | Topic | Rule to remember |
|---|---|---|
| 6 | fclose() | One close per open; check the result; never reuse the pointer |
| 7 | EOF | A return value, not data; never loop on feof(); check ferror() |
| 8 | Standard streams | stdin 0, stdout 1, stderr 2; results to stdout, errors to stderr |
| 9 | fputc() | Stream must allow writing; check for EOF; Ctrl+D is never stored |
| 10 | fgetc() | Result goes in an int; char versus int bug differs on x86 and ARM |
| 11 | putw(), getw() | Legacy; -1 equals EOF; prefer fwrite() and fread() |
C File Handling Lab Quiz
Answer each question before opening the answer. The quiz is plain HTML, so it works in any page or learning platform.
Part A: Multiple choice
- What does
fclose(fp)return when it succeeds?- A. 1
- B. 0
- C.
EOF - D. The number of bytes written
Show answer
B. It returns 0 on success and
EOFon error. - Which statement about
EOFis correct?- A. It is a special byte stored at the end of every file
- B. It is a negative
intreturned by reading functions - C. It is the character with value 26 on every system
- D. It is an unsigned
charconstant
Show answer
B.
EOFis a return value (normally -1). Nothing is stored at the end of a file. - Why is
while (!feof(fp))a poor loop condition?- A.
feof()is very slow - B. It becomes true only after a read has already failed, so the loop runs once too often
- C.
feof()always returns 0 - D. It is not allowed in C
Show answer
B. The flag is set by a failed read, so the body runs one extra time with invalid data.
- A.
- What is the POSIX file descriptor number of
stderr?- A. 0
- B. 1
- C. 2
- D. 3
Show answer
C. stdin is 0, stdout is 1 and stderr is 2.
- How is
stderrbuffered?- A. Fully buffered
- B. Line buffered
- C. Unbuffered
- D. Buffered only when it is a file
Show answer
C. stderr is unbuffered so diagnostics appear immediately.
- What happens when
fputc()is called on a stream opened with"r"?- A. It appends the character
- B. It returns
EOFand sets the error indicator - C. It truncates the file
- D. It silently does nothing and returns the character
Show answer
B. The stream is not open for writing, so the call fails (errno is EBADF in the lecture example).
- Which type should hold the result of
fgetc()?- A.
char - B.
unsigned char - C.
int - D.
short
Show answer
C. Only an
intcan hold all 256 byte values andEOF. - A.
- On a target where plain
charis unsigned, what doeschar c; while ((c = fgetc(fp)) != EOF)do at the end of the file?- A. Stops at the first byte 0xFF
- B. Never stops, because
ccan never equal -1 - C. Always works correctly
- D. Fails to compile
Show answer
B. An unsigned
charis never negative, so the comparison withEOFnever succeeds. - Why is a naive
getw()loop unsafe?- A. It is too slow
- B. A stored value of -1 cannot be told apart from
EOF - C. It only works on text files
- D. It requires the file to be open for writing
Show answer
B. Check
feof()andferror()after each call, or usefread(). - What is true about
fcloseall()with glibc?- A. It is standard C
- B. It also closes stdin, stdout and stderr and returns 0 on success
- C. It returns the number of files it closed
- D. It only closes files opened with
"w"
Show answer
B. It is a GNU extension, and it closes every stream including the standard ones.
Part B: Predict the output
- A file
t.txtcontains exactly the two charactersab. What does this program print?FILE *fp = fopen("t.txt", "r"); int n = 0; while (!feof(fp)) { fgetc(fp); n++; } printf("%d\n", n);Show answer
It prints
3. The loop readsa,b, and then a third time whenfeof()is still false; that last read fails and sets the flag. We ran this exact program to confirm. - On a machine with 4-byte
int, a program writes six integers to a file withputw()and closes it. How many bytes does the file contain?Show answer
24 bytes: six values multiplied by four bytes each.
- A file contains the bytes
41 42 FF 43 44. A program on an x86 Linux PC reads it withchar ch; while ((ch = fgetc(fp)) != EOF) count++;. What iscount?Show answer
2. The byte 0xFF becomes -1 in a signed
char, which equalsEOF, so the loop ends after41and42. This is the result shown in thefgetc()lecture.
Part C: Programming challenge
Write a program that takes a file name as a command-line argument and prints the file to the screen with every letter converted to upper case. It must report a missing file on stderr and return a failure code, and it must detect read errors.
Show a model solution
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
/* Quiz challenge: copy a text file to stdout, converting letters to upper case. */
int main(int argc, char *argv[])
{
if (argc != 2) {
fprintf(stderr, "usage: %s <file>\n", argv[0]);
return EXIT_FAILURE;
}
FILE *fp = fopen(argv[1], "r");
if (fp == NULL) {
perror(argv[1]);
return EXIT_FAILURE;
}
int c;
while ((c = fgetc(fp)) != EOF)
putchar(toupper(c));
int failed = ferror(fp);
if (failed)
fprintf(stderr, "%s: read error\n", argv[1]);
fclose(fp);
return failed ? EXIT_FAILURE : EXIT_SUCCESS;
}Running it on a two-line file prints EMBEDDED C and FILE IO 101. With a missing file it prints nope.txt: No such file or directory on stderr and exits with code 1.
C File Handling Interview Questions
These questions are asked in embedded C and Linux interviews. Say your answer aloud first, then expand it.
1. What happens if a program never calls fclose()?
At normal exit the runtime flushes and closes the stream, so little is lost. In a long-running program the stream and its descriptor leak until fopen() fails with “Too many open files”. After a crash or power cut, buffered data that was never flushed is lost, and you never see write errors that only fclose() reports.
2. Does fclose() guarantee the data is on the physical medium?
No. It flushes the stdio buffer to the operating system, which may keep the data in its cache. For power-fail safety on POSIX systems call fflush() and then fsync(fileno(fp)) before closing.
3. What is EOF, and is it stored in the file?
It is a macro for a negative integer, normally -1, that reading functions return when no more data is available or an error occurred. It is not stored in the file; the system detects the end because a read returns zero bytes.
4. Why is while (!feof(fp)) a bug?
feof() is set only after a read attempt hits the end, so the loop body runs one more time with a failed read. Put the read call in the loop condition and compare its result with EOF.
5. Why does fgetc() return int?
It must represent 256 byte values plus EOF. Storing the result in a char makes the byte 0xFF look like EOF on signed-char targets, or makes EOF undetectable on unsigned-char targets such as ARM.
6. How do you tell a read error from a normal end of file?
After the reading function returns EOF or NULL, call ferror(fp). If it is non-zero, a real error occurred; otherwise feof(fp) confirms a normal end.
7. What is the difference between stdout and stderr, and why have both?
Both are output streams, but stdout is buffered and carries results while stderr is unbuffered and carries diagnostics. Separate streams let users redirect results to a file or pipe while still seeing error messages.
8. Why can stderr text appear before earlier stdout text when output is piped?
Because stdout is fully buffered when it is not a terminal, its text waits in memory, while stderr is written immediately. Flushing stdout or changing the buffering with setvbuf() fixes the order.
9. What is the difference between putc() and fputc()?
They perform the same operation, but putc() may be implemented as a macro that evaluates its stream argument more than once. Avoid expressions with side effects in that argument, or use fputc().
10. Why should new code avoid putw() and getw()?
They are not standard C, their error reporting is ambiguous when the data contains -1, and the file format depends on the machine’s int size and byte order. Use fwrite() and fread() with fixed-width types.
11. How would you save a configuration file so a power cut cannot corrupt it?
Write the new content to a temporary file in the same directory, check every write and the result of fclose(), call fflush() and fsync(), then replace the old file with rename(), which is atomic on POSIX file systems.
12. printf() compiles on a bare-metal board but prints nothing. Why?
stdout needs a low-level write routine that sends bytes to hardware. With newlib-style libraries you supply it (commonly _write) and connect it to a UART or semihosting channel.
Common Mistakes and Troubleshooting for the Lab
| Symptom | Likely cause | Fix |
|---|---|---|
adc.bin: Permission denied | Directory not writable | Run in a folder you own or pick another path |
| No result lines appear | stdout redirected to /dev/null | Remove the redirect, or use 2>/dev/null to hide only stderr |
| Different numbers from the lecture | Generator seed or arithmetic changed | Restore seed = 2024 and the multiplier |
Implicit declaration of putw | Strict build flags such as -std=c17 | Build with GNU settings or switch to fwrite() |
| Average looks wrong | Integer division | Cast to double if you need decimals |
Best Practices Learned in This C File Handling Lab
- One function, one file handle, one open and one close on every path.
- Check the result of every open, every write that matters and every close.
- Results to stdout, diagnostics to stderr, status to the exit code.
- Never trust a value that could also be an error marker; ask the stream.
- Prefer standard functions and fixed-width types; keep legacy calls out of new code.
Performance and security notes
Reading one integer per call is fine for a few thousand samples. For continuous high-rate logging, collect samples in an array and write blocks with fwrite(). For security, never trust sizes or counts read from a file without range checks, and avoid building file paths from untrusted input.
Key Takeaways
Remember these points
- A good C file handling lab exercise combines opening, checking, closing, EOF and stream separation.
- Keep results and diagnostics on different streams.
- Use
feof()andferror()after reads that can return ambiguous values. - Always check
fclose()on files you wrote. - Know the interview answers: leaks, flushing,
EOFas an int, stdout versus stderr.
Conclusion
You now have a working logger that follows the habits taught in this part of the free C programming course, a revision table that fits on one screen, and a set of questions to test your understanding. If you could explain every interview answer in your own words, you have a solid grip on basic C file handling.
The next lectures in this free embedded C course continue with strings and formatted file input and output, and later with random access using fseek() and ftell(), so keep your lab code. You will extend it.
Frequently Asked Questions
What is the goal of this C file handling lab?
To combine closing files, checking return values, reading until end of file, using stderr for diagnostics and storing integers in a binary file, in one small program that resembles an embedded data logger.
Why does the lab use putw and getw if they are legacy functions?
Because they appear in the source material and in older code bases you will maintain. The lab uses the safe getw loop, and the exercises ask you to replace them with fwrite() and fread().
Why are the ADC samples limited to 0 to 4095?
A 12-bit converter produces 4096 different values. Staying inside that range also guarantees that no sample equals -1, but the program still uses the stream-flag loop so it stays correct for any data.
Where does the info message go, and why?
To stderr. The statistics are the program’s results and go to stdout, so a user can redirect the results into a file without capturing the progress message.
How do I run the lab on a microcontroller board?
On embedded Linux the program runs unchanged. On bare metal you need a file system library and a retargeted standard output; replace the file path with one on your storage medium and keep the error checks.
How should I prepare for file handling interview questions?
Be able to explain, with a short example, what fclose() does, why EOF needs an int, the difference between stdout and stderr, and how to detect a read error. The questions in this lecture cover exactly those points.
Are the quiz answers hidden?
Yes. Each question has a collapsible answer. Try to answer first, then expand it to check your reasoning.
Continue the Free Embedded C Course
Keep building: more file functions, formatted file input and output, and real embedded projects, all free and tested on a real compiler.

1 Comment