🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →C File Handling Basics
File handling in C explained from zero: why programs need files, how the stdio stream model works, and your first working program that writes and reads a file. Part of our free C programming course for embedded systems students.
File handling in C is the skill that turns a throw-away program into one that remembers things. Every variable you have used so far lives in RAM and vanishes when the program exits. Files let you keep configuration, logs, calibration data and results on permanent storage. This lecture opens Chapter 11 of our free C programming course and gives you the mental model you need before we touch any function in detail. If you are following this free embedded C course to work on firmware or embedded Linux, this chapter is where your code first meets real storage.
What You Will Learn
- Why RAM is not enough and what a file really is
- The two levels of file handling in C: stdio streams and system calls
- What a
FILE *is and whystdoutis also one - How
printf,scanfand friends map to their file versions - A complete, tested program that writes a file and reads it back
- Where file handling fits in embedded C programming
Prerequisites
You should be comfortable with functions, arrays, strings and pointers from the earlier chapters of this free C tutorial. You need a Linux machine (or WSL) with gcc. Every example here was compiled with gcc -Wall -Wextra -std=c11 and run on Ubuntu.
Why Programs Need Files
Primary memory (RAM) is volatile. When the program ends, or the board loses power, everything in RAM is gone. Secondary storage such as an SSD, an SD card or a NOR/NAND flash chip keeps its contents. A file is a named collection of related data stored on that permanent medium, and the operating system gives you a way to reach it by name.
Typical embedded uses of files
| Use case | What is stored | Where you meet it |
|---|---|---|
| Configuration | Baud rate, IP address, sensor thresholds | Embedded Linux gateways, routers |
| Data logging | Timestamped sensor readings | Data loggers, SD card projects |
| Calibration | ADC offsets, gain tables | Measurement instruments |
| Firmware images | Binary blobs read and verified | Bootloaders, OTA updaters |
Two Levels of File Handling in C
C programs can talk to files at two levels. The high level uses the standard library functions declared in stdio.h, such as fopen, fprintf and fclose. The low level uses operating system calls such as open, read and write on Linux. The stdio functions sit on top of the system calls and add buffering and formatting.
| Feature | High level (stdio) | Low level (system calls) |
|---|---|---|
| Header | stdio.h | fcntl.h, unistd.h |
| Handle type | FILE * | int file descriptor |
| Buffering | Done by the library | None, you manage it |
| Formatted I/O | Yes (fprintf, fscanf) | No, raw bytes only |
| Portability | Standard C, runs everywhere | POSIX, OS specific |
| Best for | Most application code | Device files, precise control |
Scope of this chapter
Chapter 11 covers the high level stdio interface only. It is easier to use, it hides buffer management, and it is the same on Linux, Windows and bare-metal toolchains. We return to system calls in the Linux system programming series.
Streams and the FILE Pointer
stdio treats every input or output source as a stream: a sequence of bytes you read or write in order. The library describes each open stream with a structure of type FILE. You never look inside it. It holds details such as the buffer, the current position and error flags. You only keep a pointer to it, a FILE *, and pass that pointer to every file function.
Three streams are opened for you before main starts: stdin, stdout and stderr. They are ordinary FILE * values. This is why the file functions feel familiar: printf(...) is simply fprintf(stdout, ...).
| Console function | Stream version | Notes |
|---|---|---|
printf(fmt, ...) | fprintf(fp, fmt, ...) | Formatted output |
scanf(fmt, ...) | fscanf(fp, fmt, ...) | Formatted input |
putchar(c) | fputc(c, fp) | One character out |
getchar() | fgetc(fp) | One character in |
puts(s) | fputs(s, fp) | fputs does not add a newline |
gets(s) | fgets(s, n, fp) | gets was removed in C11, always use fgets |
gets(). It cannot limit how many bytes it stores, so it was removed from the C standard in C11. Use fgets(buf, sizeof buf, stdin) instead.
Your First File Handling Program in C
The program below creates a small configuration-style text file, closes it, opens it again for reading and prints each line. It also shows that the same fprintf works on stdout.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *fp = fopen("notes.txt", "w");
if (fp == NULL) {
perror("fopen for write");
return EXIT_FAILURE;
}
fprintf(fp, "board=%s\n", "nucleo-f411re");
fprintf(fp, "baud=%d\n", 115200);
fputs("status=ok\n", fp);
fclose(fp);
/* same function, different stream: stdout is also a FILE * */
fprintf(stdout, "wrote notes.txt, now reading it back\n");
fp = fopen("notes.txt", "r");
if (fp == NULL) {
perror("fopen for read");
return EXIT_FAILURE;
}
char line[64];
while (fgets(line, sizeof line, fp) != NULL)
printf("read back: %s", line);
fclose(fp);
return EXIT_SUCCESS;
}
Build and run
$ gcc -Wall -Wextra -std=c11 -o first_file first_file.c
$ ./first_file
wrote notes.txt, now reading it back
read back: board=nucleo-f411re
read back: baud=115200
read back: status=ok
$ cat notes.txt
board=nucleo-f411re
baud=115200
status=ok
What each part does
fopen("notes.txt", "w")asks the library to open (and create or empty) the file for writing. It returns aFILE *, orNULLon failure.- The
NULLcheck is not optional. Without it, a failed open leads to a crash on the next call. perrorprints your text followed by the system’s reason, such as “No such file or directory”.fprintfandfputssend bytes to the stream, exactly like their console cousins.fcloseflushes the buffer and releases the stream.fgetsreads one line at a time and returnsNULLwhen the file ends.
The Standard File Workflow
Every file operation in C follows the same three steps: open, use, close. Keep this order in mind, because every bug in this chapter comes from breaking one of them.
Common Mistakes in File Handling in C
| Mistake | What happens | Fix |
|---|---|---|
Not checking fopen for NULL | Crash (segmentation fault) on first use | Always test and report with perror |
Forgetting fclose | Buffered data may be lost, descriptors leak | Close on every exit path |
Using gets() | Buffer overflow, removed in C11 | Use fgets |
Mixing up FILE * and the file name | Compile warnings or garbage output | After fopen use only the pointer |
Not compiling with -Wall | Mistakes like passing a char for a string go unnoticed | Always enable warnings |
Best Practices for File Handling in C
- Declare the
FILE *where you need it and initialise it fromfopenimmediately. - Test every
fopenresult and print a message that includes the file name. - Close the file as soon as you finish with it, not at the end of the program.
- Use
fgetsplussscanffor text input instead offscanfwhen input may be malformed. - Compile with
-Wall -Wextraand treat warnings as errors in your projects.
Embedded C programming note
On a bare-metal microcontroller there is usually no filesystem, so fopen has nothing to open until you add one (for example FatFs on an SD card) or connect the C library to your hardware. On embedded Linux, stdio works exactly as shown here. Learning the stream model now means the same code ideas carry over to both worlds.
Key Takeaways
- RAM is volatile; files keep data on permanent storage.
- stdio (high level) is portable and buffered; system calls (low level) are OS specific.
- A
FILE *identifies an open stream, andstdin,stdout,stderrare streams too. - The workflow is always open, check for NULL, read or write, close.
You now have the big picture of file handling in C. The next lecture looks at how the data is actually laid out inside a file. This free C tutorial continues with text mode versus binary mode, a topic that decides how portable your saved data will be.
Frequently Asked Questions
What is file handling in C?
It is the set of library functions, mainly in stdio.h, that let a C program create, open, read, write and close files on permanent storage.
What is a FILE pointer in C?
A FILE * points to a library-managed structure describing an open stream: its buffer, position and error state. You pass it to every file function and never access its fields directly.
Is stdout a file in C?
Yes, in the stream sense. stdout is a FILE * opened automatically at program start, so printf(x) behaves like fprintf(stdout, x).
What is the difference between stdio and system calls?
stdio functions are portable library calls with buffering and formatting. System calls such as open and write talk to the kernel directly and are specific to the operating system.
Can I use fopen on a microcontroller with no operating system?
Only if a filesystem or the C library’s low-level hooks are provided. Without them, fopen has nothing to talk to and will fail.
Why is gets() dangerous?
It has no way to limit the number of characters stored, so long input overflows the buffer. C11 removed it; use fgets.
Is this C file handling course really free?
Yes. EmbeddedPathashala offers this free C programming course, along with free embedded systems and Linux courses, for students everywhere.
Keep learning with the free embedded C course
Next up: how text files and binary files store the same number in very different ways.

1 Comment