C: File I/O

🗓 Last updated: 2026-11-30👤 Written by: Ivy✓ Reviewed by: Alex🏷 Category: C Tutorial

A file is like a safe — you must open it before use (fopen), follow the rules for storing and retrieving items (read/write modes), and always lock it when done (fclose), or your data may be lost.

Reference entries in this section: fopen fclose fgetc fputc fgets printf scanf fputs fprintf fread fwrite

1. Basic Concepts of Files

C treats all external devices as "streams". There are two types of file streams:

The operating system manages open files through a FILE structure, and we operate on it via a FILE * pointer.

(1) File Pointer

TEXT
FILE *fp;

This pointer is the "key" to all subsequent file operations. Without it, nothing can be done.


2. Opening and Closing Files

(1) fopen

C
FILE *fopen(const char *filename, const char *mode);
Mode Meaning If file doesn't exist If file exists
"r" Read only Error Read from beginning
"w" Write only Create Truncate content
"a" Append Create Append at end
"r+" Read and write Error Operate from beginning
"w+" Read and write Create Truncate content
"a+" Read and append Create Append at end
"rb" Binary read only Error Read from beginning
"wb" Binary write only Create Truncate content
"ab" Binary append Create Append at end
💡 Tip: "w" mode truncates existing files! This is the most common mistake beginners make — using "w" when they meant to append, resulting in all data being lost.

(2) fclose

TEXT
int fclose(FILE *fp);

Closing a file flushes the buffer and releases resources. Returns 0 on success, EOF on failure.

C
// Preprocessor directive
#include <stdio.h>

// Function definition
int main(void) {
    FILE *fp = fopen("data.txt", "w");
    // Conditional check
    if (fp == NULL) {
        // I/O operation
        printf("Failed to open file\n");
        // Return result
        return 1;
    }
    fprintf(fp, "Hello, File!\n");
    // I/O operation
    fclose(fp);
    // Return result
    return 0;
}
⚠️ Note: Every fopen must have a corresponding fclose. Forgetting to close a file causes memory leaks and data loss.


3. Text File I/O

(1) Character I/O: fgetc / fputc

TEXT
int fgetc(FILE *fp);
int fputc(int ch, FILE *fp);

fgetc reads one character, returning EOF at the end of file. fputc writes one character.

(2) String I/O: fgets / fputs

C
// Function definition
char *fgets(char *str, int n, FILE *fp);
// Function definition
int fputs(const char *str, FILE *fp);

fgets reads at most n-1 characters, stopping at a newline or end of file, and automatically appends '\0'.

C
// Preprocessor directive
#include <stdio.h>

// Function definition
int main(void) {
    FILE *fp = fopen("poem.txt", "w");
    // Conditional check
    if (fp == NULL) {
        // Return result
        return 1;
    }
    // I/O operation
    fputs("Riverside at sunset\n", fp);
    // I/O operation
    fputs("River flows to the sea\n", fp);
    // I/O operation
    fclose(fp);

    fp = fopen("poem.txt", "r");
    // Conditional check
    if (fp == NULL) {
        // Return result
        return 1;
    }
    char line[256];
    // While loop
    while (fgets(line, sizeof(line), fp) != NULL) {
        // I/O operation
        printf("%s", line);
    }
    // I/O operation
    fclose(fp);
    // Return result
    return 0;
}
TEXT
Riverside at sunset
River flows to the sea

4. Binary File I/O

(1) fread / fwrite

C
size_t fread(void *ptr, size_t size, size_t count, FILE *fp);
size_t fwrite(const void *ptr, size_t size, size_t count, FILE *fp);

Parameters: ptr is the data buffer, size is the byte size of each element, count is the number of elements. The return value is the actual number of elements read or written.

C
// Preprocessor directive
#include <stdio.h>

// Type definition
typedef struct {
    // Variable declaration
    int id;
    char name[20];
    // Variable declaration
    float score;
} Student;

// Function definition
int main(void) {
    Student stu = {1, "Alice", 92.5f};

    FILE *fp = fopen("student.dat", "wb");
    // Conditional check
    if (fp == NULL) {
        // Return result
        return 1;
    }
    // I/O operation
    fwrite(&stu, sizeof(Student), 1, fp);
    // I/O operation
    fclose(fp);

    Student read_stu;
    fp = fopen("student.dat", "rb");
    // Conditional check
    if (fp == NULL) {
        // Return result
        return 1;
    }
    // I/O operation
    fread(&read_stu, sizeof(Student), 1, fp);
    // I/O operation
    fclose(fp);

    // I/O operation
    printf("ID: %d, Name: %s, Score: %.1f\n",
           read_stu.id, read_stu.name, read_stu.score);
    // Return result
    return 0;
}
TEXT
ID: 1, Name: Alice, Score: 92.5
💡 Tip: Binary mode is ideal for storing struct data — it's efficient and preserves content exactly. Text mode may handle newline characters differently across operating systems, while binary mode saves everything as-is.


5. Formatted I/O

(1) fprintf / fscanf

C
// Function definition
int fprintf(FILE *fp, const char *format, ...);
// Function definition
int fscanf(FILE *fp, const char *format, ...);

Their usage is identical to printf/scanf, just with an additional file pointer parameter.

C
// Preprocessor directive
#include <stdio.h>

// Function definition
int main(void) {
    FILE *fp = fopen("scores.txt", "w");
    // Conditional check
    if (fp == NULL) {
        // Return result
        return 1;
    }
    fprintf(fp, "%s %d %.1f\n", "Bob", 2, 88.0);
    fprintf(fp, "%s %d %.1f\n", "Carol", 3, 95.5);
    // I/O operation
    fclose(fp);

    fp = fopen("scores.txt", "r");
    // Conditional check
    if (fp == NULL) {
        // Return result
        return 1;
    }
    char name[20];
    // Variable declaration
    int id;
    // Variable declaration
    float score;
    // While loop
    while (fscanf(fp, "%s %d %f", name, &id, &score) == 3) {
        // I/O operation
        printf("Name: %s, ID: %d, Score: %.1f\n", name, id, score);
    }
    // I/O operation
    fclose(fp);
    // Return result
    return 0;
}
TEXT
Name: Bob, ID: 2, Score: 88.0
Name: Carol, ID: 3, Score: 95.5

6. File Position Pointer

Every open file has a "position pointer" indicating the current read/write location. It's like a bookmark while reading — wherever you've read to, the bookmark marks that spot.

(1) fseek

C
// Function definition
int fseek(FILE *fp, long offset, int origin);
origin Meaning
SEEK_SET Beginning of file
SEEK_CUR Current position
SEEK_END End of file

(2) ftell / rewind

TEXT
long ftell(FILE *fp);
void rewind(FILE *fp);

ftell returns the current position (byte offset from the beginning of the file). rewind is equivalent to fseek(fp, 0, SEEK_SET).

▶ Example

Using fseek and ftell to calculate file size:

▶ Try it Yourself

▶ Example

Random access to a specific record in a binary file:

▶ Try it Yourself
TEXT
Record 2: ID=2, Name=Bob, Score=88.0
💡 Tip: This is the principle behind "random access" in databases! By calculating the offset, you can jump directly to a specific position without traversing from the beginning.


7. Other File Functions

(1) feof

C
// Function definition
int feof(FILE *fp);

Checks whether the end of file has been reached. Returns non-zero at EOF. Note: feof only becomes true after a read operation has failed, not as a pre-check.

(2) fflush

TEXT
int fflush(FILE *fp);

Forces a flush of the buffer, writing buffered data to the file. Calling fflush on an input stream results in undefined behavior.

(3) remove / rename

C
// Function definition
int remove(const char *filename);
// Function definition
int rename(const char *old, const char *new);

Delete and rename files. Return 0 on success.


8. General Pattern for File Operations

Most file operations follow this pattern:

  1. Open the file with fopen and check the return value
  2. Read or write data in a loop
  3. Close the file with fclose
C
// Preprocessor directive
#include <stdio.h>

// Function definition
int main(void) {
    FILE *fp = fopen("input.txt", "r");
    // Conditional check
    if (fp == NULL) {
        perror("fopen");
        // Return result
        return 1;
    }

    // Variable declaration
    int ch;
    // While loop
    while ((ch = fgetc(fp)) != EOF) {
        // I/O operation
        putchar(ch);
    }

    // I/O operation
    fclose(fp);
    // Return result
    return 0;
}
⚠️ Note: Checking the fopen return value is an absolute rule! The file might not exist, you might lack permissions, or the disk could be full — using a null pointer without checking will crash immediately.

Reference entries in this section: fopen fclose fgetc fputc fgets printf scanf fputs fprintf fread fwrite

❓ FAQ

Q fopen returns NULL but the file clearly exists. What's wrong?
A It is almost always a path issue. Relative paths are based on the program's current working directory, not where the source file lives. When running from an IDE, the working directory may differ from what you expect. Use fopen("/absolute/path/file.txt", "r") to confirm.
Q What is the difference between text mode and binary mode?
A On Windows, text mode translates between \n and \r\n during read/write, while binary mode performs no translation. On Linux and macOS, there is no difference — \n is already the native line ending everywhere. Using "b" mode explicitly is portable practice.
Q Are files written with fwrite compatible across different compilers?
A Not necessarily. Memory alignment, byte order (endianness), and basic type sizes may all differ between platforms. Cross-platform binary files require manual serialization — write each field one at a time in a defined byte order.
Q Why can't feof be used as a loop condition?
A feof only returns true after a read operation has already passed past the end of file. Using while (!feof(fp)) causes one extra iteration that processes invalid data. Always use the return value of fread, fgets, or fscanf as the loop condition instead.
Q How can I get the list of files in a directory using C?
A C's standard library has no directory listing function. The POSIX API provides opendir and readdir (use dirent.h), and Windows has FindFirstFile. Both work differently, so portable code needs a platform-specific wrapper.
Q How do I determine the size of my array in C?
A For a local stack array, use sizeof(arr) / sizeof(arr[0]). For a pointer returned by malloc, there is no way — you must keep a separate count variable that you pass around alongside the pointer.
Q Difference between malloc and calloc?
A malloc(bytes) allocates uninitialized memory. calloc(n, element_size) allocates n times element_size bytes and zeroes every byte. Use calloc for file buffers or any array that depends on zero initialization, and malloc for performance-critical cases where you overwrite immediately.
Q With arrays, why is it the case that a[5] == 5[a]?
A Because a[5] is syntactic sugar for pointer arithmetic *(a + 5), and 5[a] is *(5 + a). Integer addition is commutative, so they evaluate to the exact same memory address. This is a famous C trivia example.

▶ Example — fseek ftell rewind for random access

▶ Try it Yourself
TEXT
Pos at 5: 5 -> W
Pos -3 from end: 7 -> r
After rewind: 0 -> H

📖 Summary

📝 Exercises

  1. Write a program that counts the number of lines, words, and characters in a text file
  2. Implement a simple file copy program that reads a source file in binary mode and writes to a destination file
  3. Write a program that saves an array of structs to a binary file, then reads them back and prints them out
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

Content reviewed by MOTO · Found an error? Report it

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏