Course contentsShow
← C
Lesson 1092 of 1,21915. Systems ProgrammingFree lesson

File descriptors vs FILE pointers

File descriptors vs FILE pointers

What you'll learn: The difference between low-level integer handles used by the operating system and the high-level buffered streams used by C programs.

When you interact with files in C, you have two ways to do it: the "low-level" way and the "high-level" way. While they both get the job done, they operate at different layers of your computer.

The Raw Handle: File Descriptors

Think of a file descriptor (fd) as a claim check at a coat room. It is a simple non-negative integer (0, 1, 2, 3...) that the Operating System uses to track an open file.

When you use functions like open(), read(), or write(), you are talking directly to the OS kernel. The kernel doesn't care about formatting or buffering; it just sees a stream of raw bytes. It’s fast and powerful, but it’s "unbuffered," meaning every single call to write() triggers a context switch to the OS, which can be slow if done too often.

The Smart Wrapper: FILE Pointers

A FILE pointer (e.g., FILE *fp) is a sophisticated wrapper around a file descriptor. When you use fopen(), fprintf(), or fgets(), you are using the C Standard Library.

The FILE structure contains a hidden file descriptor, but it adds a buffer—a temporary storage area in your program's memory. Instead of bothering the OS for every single character you type, the library waits until the buffer is full and then sends a large chunk of data all at once using the file descriptor. This is like waiting to fill a grocery bag before walking to the car, rather than carrying every individual grape one by one.

Seeing both in action

You can actually extract the raw descriptor from a FILE pointer using the fileno() function.

#include <stdio.h>
#include <unistd.h>

int main() {
    // A high-level FILE pointer
    FILE *fp = fopen("example.txt", "w");
    
    // Extract the underlying low-level file descriptor
    int fd = fileno(fp);
    
    printf("The FILE pointer is at address: %p\n", (void*)fp);
    printf("The underlying file descriptor is: %d\n", fd);
    
    fclose(fp);
    return 0;
}

Which one to use?

  • Use FILE pointers for most tasks. They are portable, easier to use, and usually faster because of buffering.
  • Use file descriptors when you are doing systems programming, like redirecting input/output, working with network sockets, or when you need fine-grained control over exactly when data hits the disk.

Key takeaway

A file descriptor is a raw integer ID used by the OS, while a FILE pointer is a feature-rich C object that manages a descriptor and a buffer for better efficiency.