C stdio.h Header

Beginner
6 min read
Updated: Oct 2026
3 examples
Live preview

What Is stdio.h?

<stdio.h> is the C standard input/output header. It gives you printf, scanf, file functions like fopen / fgets, and the streams stdin, stdout, and stderr.

Remember
#include <stdio.h>

printf / scanf     → formatted console I/O
fopen / fclose     → open and close files
fprintf / fgets    → formatted / line I/O on FILE*

stdin  → keyboard (default)
stdout → screen (default)
stderr → errors (unbuffered-ish)

FILE *fp;   EOF means end / failure
always check fopen for NULL
UsePrefer
Print to the screenprintf
Write to a file or stderrfprintf(fp, ...)
Explain a failed fopenperror + errno

How to Use stdio.h in C

Include the header, pick a stream or file, then read or write with matching format strings.

  1. Add #include <stdio.h> at the top of the file.
  2. Use printf / scanf for the console, or fopen for files.
  3. Check return values: fopen for NULL, scanf for match count.
  4. Call fclose when done with a file (or exit—stdio flushes, but closing is clearer).
PieceRequired?Role
#include <stdio.h>YesDeclares I/O functions and FILE
Format stringYes%d, %s, %f, … for typed I/O
FILE *For filesHandle from fopen

Pseudocode

Pseudocode
include stdio.h

// console
printf("Hello %s\n", name)
scanf("%d", &n)     // need & for scalars

// file
fp = fopen("data.txt", "w")
if fp is NULL:
    perror("fopen")
    exit
fprintf(fp, "n = %d\n", n)
fclose(fp)

// read a line safely
fgets(buf, sizeof(buf), fp_or_stdin)

Cheat Sheet

Core calls and modes you will use every day.

TopicDetail
Header#include <stdio.h>
printfFormatted write to stdout
scanfFormatted read from stdin (use &)
fopen(path, "r")Open for reading; "w" write; "a" append
fgets(buf, n, fp)Read up to n-1 chars (safer than gets)
fprintfprintf to any FILE*
EOFEnd-of-file / no more input (usually -1)
Common specs%d int, %f double, %s string, %c char

Live Preview

Simulate common stdio.h patterns: formats, fopen modes, and a failed open with perror.

Browser simulation of stdio ideas (same concepts as the C examples below).

Result
printf("n = %d, pi ≈ %.2f\n", 42, 3.14159);
→ n = 42, pi ≈ 3.14

%d → int    %f → float/double
%s → string  %c → char

Worked Walkthrough — Write Then Read a File

Create note.txt, write one line, close, reopen for reading, and print the line with fgets.

Calculation
1) fp = fopen("note.txt", "w")
   NULL? → fail + perror
   fprintf(fp, "hello\n")
   fclose(fp)

2) fp = fopen("note.txt", "r")
   fgets(buf, sizeof(buf), fp)
   → buf = "hello\n"
   printf("%s", buf)
   fclose(fp)

Check at each open — never use a NULL FILE*. ✓

C Examples

Compile with gcc file.c -std=c11 -o out. File examples create note.txt in the current directory.

Example 1 — printf and scanf

Print a prompt, read an integer with &, then echo it with a format string.

C
#include <stdio.h>

int main(void) {
    int age;

    printf("Enter age: ");
    if (scanf("%d", &age) != 1) {
        printf("Invalid input\n");
        return 1;
    }
    printf("You entered: %d\n", age);

    return 0;
}

How It Works

  1. Prompt with printf. Text goes to stdout (usually the terminal).
  2. Pass an address. scanf("%d", &age) stores the number into age.
  3. Check the return. scanf returns how many items it assigned; 1 means success.
  4. Echo with %d. printf substitutes the int into the format string.

Example 2 — Write and Read a Text File

Open a file for writing with fprintf, then reopen it and read a line with fgets.

C
#include <stdio.h>

int main(void) {
    FILE *fp;
    char line[64];

    fp = fopen("note.txt", "w");
    if (fp == NULL) {
        perror("fopen write");
        return 1;
    }
    fprintf(fp, "hello from C\n");
    fclose(fp);

    fp = fopen("note.txt", "r");
    if (fp == NULL) {
        perror("fopen read");
        return 1;
    }
    if (fgets(line, sizeof(line), fp) != NULL) {
        printf("Read: %s", line);
    }
    fclose(fp);

    return 0;
}

How It Works

  1. Open for write. "w" creates or truncates note.txt.
  2. fprintf to the FILE*. Same formats as printf, but to the file.
  3. Close, then reopen. "r" starts reading from the beginning.
  4. fgets is bounded. It reads at most sizeof(line) - 1 characters—safer than gets.

Example 3 — Handle a Failed fopen

Always test for NULL. Use perror (and errno) to show why the open failed.

C
#include <stdio.h>

int main(void) {
    FILE *fp = fopen("no_such_file.txt", "r");
    if (fp == NULL) {
        perror("fopen");
        return 1;
    }
    fclose(fp);
    return 0;
}

How It Works

  1. fopen fails. Missing file in "r" mode returns NULL.
  2. Check immediately. Never call fgets or fprintf on a null pointer.
  3. perror explains. It prints your label plus the message from errno.
  4. Exit with an error. Returning 1 signals failure to the shell.

Edge Cases & Pitfalls

Check these before shipping I/O code.

scanf

Always pass & for scalars

scanf("%d", age) without & is undefined behavior. Arrays already decay to pointers.

buffer

Never use gets()

gets cannot bound the buffer. Prefer fgets(buf, sizeof(buf), stdin).

null

Check fopen for NULL

Missing paths, permissions, or full disks return NULL. Call perror and stop.

eof

Store fgetc in an int

EOF is not a valid char value on all systems. Use int c = fgetc(fp);.

Performance Notes

ApproachCostBest for
printf / fprintfFormatting + buffered I/OHuman-readable text
fgets / line loopsModerate; still bufferedText files line by line
fread / fwriteFewer syscalls in bulkBinary or large blocks

stdio buffers output for speed. Force a flush with fflush when a prompt must appear before the next read.

Key Takeaways

  • Role: formatted console and file I/O via FILE* streams.
  • Safety: check fopen, bound reads with fgets, pass & to scanf.
  • Streams: stdout for normal output, stderr for errors.
  • Errors: perror after failed opens explains errno.

One line: stdio.h is how C talks to the keyboard, screen, and files—always check opens and bound your buffers.

Frequently Asked Questions

stdio.h is the Standard Input/Output header. It declares printf, scanf, fopen, fclose, fgets, and related functions for console and file I/O. It also defines FILE, EOF, and the standard streams stdin, stdout, and stderr.
printf writes formatted text to stdout. fprintf takes a FILE* first, so you can write to a file or any stream: fprintf(fp, "%d\n", n) or fprintf(stderr, "error\n").
scanf stores into variables, so it needs addresses. For int x use scanf("%d", &x). Arrays decay to pointers, so scanf("%99s", name) does not need & on the array name.
EOF is a macro (usually -1) meaning end-of-file or no more input. fgetc returns EOF as an int. Do not store fgetc results in a char—use int so EOF is distinguishable.
perror prints your message, a colon, then a system error text based on errno. Call it after a failed fopen or similar call to see why it failed.
fflush forces buffered output to be written now. Call fflush(stdout) before a prompt without a newline, or fflush(fp) when you need data on disk before continuing.

Next: stdlib.h

Allocate memory, convert strings, and exit with status codes.

stdlib.h tutorial →

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.

9 people found this page helpful