100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace

C File I/O Cheat Sheet

C File I/O Cheat Sheet

Covers reading and writing text and binary files in C using fopen, fread and fwrite, formatted I/O, and file positioning functions.

2 PagesIntermediateApr 12, 2026

Opening and Reading Text Files

Open a file stream and read it line by line.

c
#include <stdio.h>FILE *fp = fopen("data.txt", "r");   // Modes: r, w, a, r+, w+, a+if (fp == NULL) {    perror("fopen failed");    return 1;}char line[256];while (fgets(line, sizeof(line), fp) != NULL) {    printf("%s", line);              // fgets keeps the trailing newline}fclose(fp);

Writing and Appending

Formatted and raw text output to a file.

c
FILE *out = fopen("output.txt", "w");fprintf(out, "Score: %d, Name: %s\n", 95, "Alice");  // Formatted writefputs("Another line\n", out);                        // Write a stringfputc('!', out);                                     // Write a single charfclose(out);FILE *log = fopen("app.log", "a");   // Append mode: writes go to end of filefprintf(log, "Event logged\n");fclose(log);

Binary I/O

Reading and writing raw struct data with fread/fwrite.

c
struct Record { int id; double value; };struct Record r = {1, 3.14};FILE *bin = fopen("data.bin", "wb");fwrite(&r, sizeof(struct Record), 1, bin);   // Write raw bytesfclose(bin);struct Record r2;FILE *in = fopen("data.bin", "rb");fread(&r2, sizeof(struct Record), 1, in);    // Read raw bytes backfclose(in);

Functions & Positioning

Key stdio.h functions beyond basic read/write.

  • fopen / fclose- Open and close a FILE stream; always check fopen's return value for NULL
  • fread / fwrite- Binary block I/O; both return the number of items actually transferred
  • fseek / ftell- fseek(fp, offset, SEEK_SET|SEEK_CUR|SEEK_END) moves the position; ftell reports it
  • rewind(fp)- Resets the file position indicator back to the beginning of the stream
  • feof / ferror- Check end-of-file or error state on a stream, typically after a read loop
  • stdin/stdout/stderr- Predefined streams available without calling fopen
  • fflush(fp)- Forces buffered output to be written immediately, e.g. before a crash-prone call
Pro Tip

Always check the return value of fread/fwrite against the expected item count — a short read or write (e.g. from a full disk) is silently possible and easy to miss.

Was this cheat sheet helpful?

Explore Topics

#CFileIO#CFileIOCheatSheet#Programming#Intermediate#Opening#Reading#Text#Files#Functions#CheatSheet#SkillVeris
Advertisement
Sri Hayavadhana Info-Tech

Professional Web Designing Services

  • Responsive Websites
  • E-commerce Solutions
  • SEO Friendly Design
  • Fast & Secure
  • Support & Maintenance
Get a Free Quote

Share this Cheat Sheet