What are C File Handling Basics-Free C Programming Course

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

Free C Programming Course · Chapter 11 · Lecture 1

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 why stdout is also one
  • How printf, scanf and 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.

Lifetime of data: RAM only vs saved to a file
Program starts Data in RAM variables Program exits RAM contents lost
Program starts Data in RAM variables Write to file Data survives on disk Next run reads it back

Typical embedded uses of files

Use caseWhat is storedWhere you meet it
ConfigurationBaud rate, IP address, sensor thresholdsEmbedded Linux gateways, routers
Data loggingTimestamped sensor readingsData loggers, SD card projects
CalibrationADC offsets, gain tablesMeasurement instruments
Firmware imagesBinary blobs read and verifiedBootloaders, 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.

Layers between your code and the disk
Your C program
stdio: FILE *, fopen, fprintf, fgets (adds a buffer)
System calls: open, read, write, close
Kernel: VFS and filesystem driver
Storage device: SSD, SD card, flash
FeatureHigh level (stdio)Low level (system calls)
Headerstdio.hfcntl.h, unistd.h
Handle typeFILE *int file descriptor
BufferingDone by the libraryNone, you manage it
Formatted I/OYes (fprintf, fscanf)No, raw bytes only
PortabilityStandard C, runs everywherePOSIX, OS specific
Best forMost application codeDevice 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 functionStream versionNotes
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
Warning: older books still show 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 a FILE *, or NULL on failure.
  • The NULL check is not optional. Without it, a failed open leads to a crash on the next call.
  • perror prints your text followed by the system’s reason, such as “No such file or directory”.
  • fprintf and fputs send bytes to the stream, exactly like their console cousins.
  • fclose flushes the buffer and releases the stream.
  • fgets reads one line at a time and returns NULL when 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.

Open, check, use, close
1. FILE *fp 2. fopen() 3. fp == NULL ? 4. read / write 5. fclose()

Common Mistakes in File Handling in C

MistakeWhat happensFix
Not checking fopen for NULLCrash (segmentation fault) on first useAlways test and report with perror
Forgetting fcloseBuffered data may be lost, descriptors leakClose on every exit path
Using gets()Buffer overflow, removed in C11Use fgets
Mixing up FILE * and the file nameCompile warnings or garbage outputAfter fopen use only the pointer
Not compiling with -WallMistakes like passing a char for a string go unnoticedAlways enable warnings

Best Practices for File Handling in C

  • Declare the FILE * where you need it and initialise it from fopen immediately.
  • Test every fopen result 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 fgets plus sscanf for text input instead of fscanf when input may be malformed.
  • Compile with -Wall -Wextra and 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, and stdin, stdout, stderr are 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.

💬 Need help or career guidance? Ask us!Contact Us →

1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →