C stdio.h Library Reference
Complete reference for stdio.h - all printf, scanf, and file functions with prototypes, parameters, and examples.
Track Your Progress
Sign in to save your learning progress
What You Will Learn
- ✓Know all printf/scanf variants
- ✓Understand file operation functions
- ✓Use character I/O functions
- ✓Reference function prototypes quickly
?Why is stdio.h Important?
Every C program you'll ever write likely starts with #include <stdio.h>. It's the foundation of all input/output operations in C.
Console I/O
printf, scanf, getchar
File Operations
fopen, fread, fwrite
Formatted Output
%d, %f, %s specifiers
New to I/O? Start with the beginner-friendly Input/Output Tutorial first. This page is a quick reference for all stdio.h functions.
01Introduction to stdio.h
What is stdio.h?
<stdio.h> (Standard Input/Output) is the most commonly used header in C. It provides functions for console I/O, file handling, and formatted output.
Key Functions Overview
| Category | Functions |
|---|---|
| Output | printf, fprintf, sprintf, snprintf |
| Input | scanf, fscanf, sscanf |
| Character | getchar, putchar, getc, putc, fgetc, fputc |
| String | gets, puts, fgets, fputs |
| File | fopen, fclose, fread, fwrite, fseek, ftell |
02printf() Family - Formatted Output
printf() - Print to Console
printf("Name: %s, Age: %d\n", "Alice", 25);// Output: Name: Alice, Age: 25fprintf() - Print to File/Stream
FILE *fp = fopen("log.txt", "w");fprintf(fp, "Error code: %d\n", 404);fprintf(stderr, "Error occurred!\n"); // Print to error streamfclose(fp);sprintf() - Print to String
char buffer[100];sprintf(buffer, "Score: %d/%d", 85, 100);printf("%s\n", buffer); // Output: Score: 85/100snprintf() - Safe Print to String
char buffer[20];snprintf(buffer, sizeof(buffer), "Long text: %s", "This is a very long string");// Safe: Won't overflow buffer!✓Recommended: Always use snprintf() over sprintf() to prevent buffer overflow!
03scanf() Family - Formatted Input
scanf() - Read from Console
int age;char name[50];printf("Enter name and age: ");scanf("%s %d", name, &age); // Note: & for non-arraysprintf("Hello %s, you are %d years old\n", name, age);fscanf() - Read from File
FILE *fp = fopen("data.txt", "r");int id;float price;fscanf(fp, "%d %f", &id, &price);fclose(fp);sscanf() - Read from String
char data[] = "John 25 85.5";char name[20];int age;float score;sscanf(data, "%s %d %f", name, &age, &score);// name="John", age=25, score=85.504Character I/O Functions
| Function | Prototype | Description |
|---|---|---|
| getchar() | int getchar(void) | Read one char from stdin |
| putchar() | int putchar(int c) | Write one char to stdout |
| fgetc() | int fgetc(FILE *stream) | Read char from file |
| fputc() | int fputc(int c, FILE *stream) | Write char to file |
| ungetc() | int ungetc(int c, FILE *stream) | Push char back to stream |
1#include <stdio.h>23int main() {4 // Read and echo characters until Enter5 printf("Type something: ");6 int ch;7 while ((ch = getchar()) != '\n') {8 putchar(ch); // Echo each character9 }10 putchar('\n');11 12 // File character I/O13 FILE *fp = fopen("test.txt", "r");14 if (fp) {15 while ((ch = fgetc(fp)) != EOF) {16 putchar(ch); // Print file contents17 }18 fclose(fp);19 }20 return 0;21}05String I/O Functions
fgets() - Safe String Input
char name[50];printf("Enter name: ");fgets(name, sizeof(name), stdin); // Safe: won't overflow!// Note: fgets includes the newline characterfputs() - Write String to Stream
fputs("Hello World!\n", stdout); // To consoleFILE *fp = fopen("out.txt", "w");fputs("Written to file", fp);fclose(fp);puts() - Simple String Output
puts("Hello World!"); // Automatically adds newline// Same as: printf("Hello World!\n");Never Use gets()!
gets() is deprecated and dangerous — no buffer size limit causes overflow. Always use fgets() instead!
06File Operations
| Function | Prototype | Description |
|---|---|---|
| fopen() | FILE *fopen(const char *path, const char *mode) | Open file |
| fclose() | int fclose(FILE *stream) | Close file |
| fread() | size_t fread(void *ptr, size_t size, size_t n, FILE *s) | Read binary data |
| fwrite() | size_t fwrite(const void *ptr, size_t size, size_t n, FILE *s) | Write binary data |
| fseek() | int fseek(FILE *stream, long offset, int whence) | Move file position |
| ftell() | long ftell(FILE *stream) | Get current position |
| rewind() | void rewind(FILE *stream) | Go to file start |
| feof() | int feof(FILE *stream) | Check end of file |
| ferror() | int ferror(FILE *stream) | Check for error |
1#include <stdio.h>23int main() {4 // Write to file5 FILE *fp = fopen("data.txt", "w");6 if (fp == NULL) {7 perror("Error opening file");8 return 1;9 }10 fprintf(fp, "Hello, File!\n");11 fclose(fp);12 13 // Read from file14 fp = fopen("data.txt", "r");15 char buffer[100];16 while (fgets(buffer, sizeof(buffer), fp) != NULL) {17 printf("%s", buffer);18 }19 fclose(fp);20 21 return 0;22}07File Opening Modes
| Mode | Description | If File Exists | If Not Exists |
|---|---|---|---|
| "r" | Read | Open | Error (NULL) |
| "w" | Write | Truncate (empty) | Create |
| "a" | Append | Open at end | Create |
| "r+" | Read/Write | Open | Error |
| "w+" | Read/Write | Truncate | Create |
| "rb" | Read binary | Add 'b' for binary mode | |
08Standard Streams
stdinStandard Input (keyboard)
stdoutStandard Output (console)
stderrStandard Error (errors)
!Code Pitfalls: Common Mistakes & What to Watch For
Copied code often generates printf/scanf code with format string vulnerabilities or mismatched format specifiers.
If you search online to "print user input," it might generate printf(user_input) instead of printf("%s", user_input). This is a critical security vulnerability — attackers can crash your program or execute arbitrary code with format strings like %n.
The Trap: Online sources focus on functionality, not security. They might also mismatch format specifiers (using %d for size_t, %f for double in scanf), leading to undefined behavior, wrong output, or crashes. The bugs often work in testing but fail with different inputs.
The Reality: Never pass user input as the first argument to printf(). Always use literal format strings. Match specifiers to types exactly: %d for int, %zu for size_t, %f for float (printf) but %lf for double (scanf). Compile with -Wformat to catch mismatches.
10Frequently Asked Questions
Q:What does fflush(stdout) do and when should I use it?
A: fflush(stdout) forces buffered output to be written immediately. stdout is line-buffered on terminals, so output without a newline may not appear until later. Use it before asking for input with prompts like "Enter name: " to ensure the prompt displays.
Q:Why should I use fgets() instead of gets()?
A: gets() has no buffer size limit — it's a security vulnerability and was removed from C11. fgets(buf, size, stdin) is safe because you specify the maximum characters to read.
Q:What's the difference between printf and fprintf?
A: printf() writes to stdout (the screen). fprintf() writes to any FILE* — a file, stderr, or even stdout explicitly. Use fprintf(stderr, ...) for error messages.
Q:Why does fopen() return NULL?
A: The file doesn't exist (for "r" mode), you don't have permission, or the path is wrong. Always check for NULL and use perror() to see the actual error.
Q:When do I use "rb" vs "r" mode?
A: Use "rb" (binary) for non-text files (images, executables, data). Use "r" (text) for .txt, .c, etc. On Windows, text mode translates \\r\\n to \\n — binary mode reads bytes exactly as stored.
✓Additional Tips
Buffer Flushing
Output to stdout is line-buffered by default. If you need immediate output (e.g., progress indicators), call fflush(stdout) after printing. This forces buffered data to be written immediately.
Binary vs Text Mode
On Windows, text mode ("r", "w") converts \\n to \\r\\n on output and vice versa on input. Binary mode ("rb", "wb") reads/writes bytes exactly. Always use binary mode for non-text files (images, executables).
Error Checking
Always check return values! fopen() returns NULL on failure.printf() returns number of characters written. Use ferror() and feof()to diagnose stream problems.
10Summary
Key Functions
Output:
printf, fprintf, sprintf, snprintf
Input:
scanf, fscanf, sscanf, fgets
Character:
getchar, putchar, fgetc, fputc
File:
fopen, fclose, fread, fwrite
11Practical I/O Tips
Buffered vs Unbuffered I/O
stdio uses buffering by default for efficiency. Use fflush(stdout) to force output before expected, or setvbuf() to change buffering mode. stderr is typically unbuffered so error messages appear immediately.
Binary vs Text Mode
On Windows, text mode converts \n to \r\n. Use "rb" and "wb" for binary files to prevent corruption. On Unix, there's no difference, but using binary mode makes code portable.
Safer Alternatives
Always prefer fgets() over gets() (removed in C11), snprintf() over sprintf(), and check scanf return values. These prevent buffer overflows and detect input errors.
Handle Errors Gracefully
Always check return values: fopen() returns NULL on failure,scanf() returns the number of items read. Useferror() and feof() to distinguish between errors and end-of-file conditions.
Close What You Open
For every fopen(), there should be a correspondingfclose(). File handles are limited resources—leaving them open causes resource leaks and can prevent other processes from accessing files.
Test Your Knowledge
Related Tutorials
Input/Output in C
Make your programs interactive! Learn to display output with printf() and read user input with scanf(). Essential for every C program.
C Standard Library Overview
A comprehensive overview of all C standard library headers. Learn what each header provides, when to use them, and how they work together.
C stdlib.h Library Reference
Complete reference for stdlib.h - memory allocation, string conversion, random numbers, sorting, and program control.
Have Feedback?
Found something missing or have ideas to improve this tutorial? Let us know on GitHub!