C File Handling Basics

Intermediate
6 min read
Updated: Nov 2026
1 example

What Is File Handling Basics?

C treats files as streams of bytes. A text stream is organized into lines and may translate \n to the platform's line ending; a binary stream is raw bytes. Every file program follows the same steps: open with fopen, read or write, and close with fclose.

Remember
FILE *fp = fopen("data.txt", "r");   /* 1. open  */
if (!fp) { /* error */ }
/* 2. use: fgets / fprintf / fread / fwrite */
fclose(fp);                          /* 3. close */

Cheat Sheet

Keep these facts handy while you work with File Handling Basics in C.

TopicDetail
Header<stdio.h>
HandleFILE *
Standard streamsstdin, stdout, stderr
AlwaysCheck fopen, then fclose

C Examples

Compile each example with gcc file.c -std=c11 -Wall -o out. Next: File Pointers.

Example 1 — Write then read a short file

The complete open-use-close cycle.

C
#include <stdio.h>

int main(void) {
    FILE *out = fopen("notes.txt", "w");
    if (!out) { perror("notes.txt"); return 1; }
    fputs("learning C file I/O\n", out);
    fclose(out);

    char buf[64];
    FILE *in = fopen("notes.txt", "r");
    if (!in) { perror("notes.txt"); return 1; }
    if (fgets(buf, sizeof buf, in)) printf("read: %s", buf);
    fclose(in);
    return 0;
}

How It Works

  1. fputs writes the string and the newline already in it.
  2. Each fopen is paired with an fclose.
  3. perror prints a readable message if a file cannot be opened.

Edge Cases & Pitfalls

Check these before relying on File Handling Basics in real programs.

path

Relative paths

Relative file names resolve against the program's current working directory, not the source file's folder.

mode

Wrong mode

"w" erases an existing file. Use "a" to append.

Key Takeaways

  • Stream: bytes in, bytes out.
  • Pair: open with close.
  • Mode: matters for existing data.

One line: C treats files as streams of bytes.

Frequently Asked Questions

Call fopen("name", "mode") and check that the result is not NULL. Use fclose when you are done.
To the current working directory of the running process, which depends on how and where you launch the program.
Continue with "C File Pointers" next. Use FILE * to represent streams, including stdin, stdout, and stderr. The C File Handling hub lists every topic in order.

Next: File Pointers

Use FILE * to represent streams, including stdin, stdout, and stderr.

Continue →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful