Chapter 26Beginner

C stdio.h Library Reference

Complete reference for stdio.h - all printf, scanf, and file functions with prototypes, parameters, and examples.

20 min readUpdated 2024-12-16
stdio.hprintfscanffopenfclosefgetsfputs

What You Will Learn

  • Know all printf/scanf variants
  • Understand file operation functions
  • Use character I/O functions
  • Reference function prototypes quickly

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.

📖 New to I/O? Start with the beginner-friendly Input/Output Tutorial first.

📋 Key Functions Overview

CategoryFunctions
Outputprintf, fprintf, sprintf, snprintf
Inputscanf, fscanf, sscanf
Charactergetchar, putchar, getc, putc, fgetc, fputc
Stringgets, puts, fgets, fputs
Filefopen, fclose, fread, fwrite, fseek, ftell

02printf() Family - Formatted Output

printf() - Print to Console

int printf(const char *format, ...);
format: Format string with specifiers
...: Values to print
Returns: Number of characters printed
main.c
C
printf("Name: %s, Age: %d\n", "Alice", 25);
// Output: Name: Alice, Age: 25

fprintf() - Print to File/Stream

int fprintf(FILE *stream, const char *format, ...);
stream: File pointer (FILE *)
format: Format string
main.c
C
FILE *fp = fopen("log.txt", "w");
fprintf(fp, "Error code: %d\n", 404);
fprintf(stderr, "Error occurred!\n"); // Print to error stream
fclose(fp);

sprintf() - Print to String

int sprintf(char *str, const char *format, ...);
str: Destination buffer
format: Format string
main.c
C
char buffer[100];
sprintf(buffer, "Score: %d/%d", 85, 100);
printf("%s\n", buffer); // Output: Score: 85/100

snprintf() - Safe Print to String

int snprintf(char *str, size_t size, const char *format, ...);
str: Destination buffer
size: Max bytes to write (including \\0)
main.c
C
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 scanf(const char *format, ...);
format: Format string with specifiers
...: Pointers to variables
Returns: Number of items successfully read
main.c
C
int age;
char name[50];
printf("Enter name and age: ");
scanf("%s %d", name, &age); // Note: & for non-arrays
printf("Hello %s, you are %d years old\n", name, age);

fscanf() - Read from File

int fscanf(FILE *stream, const char *format, ...);
main.c
C
FILE *fp = fopen("data.txt", "r");
int id;
float price;
fscanf(fp, "%d %f", &id, &price);
fclose(fp);

sscanf() - Read from String

int sscanf(const char *str, const char *format, ...);
main.c
C
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.5

04Character I/O Functions

FunctionPrototypeDescription
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
char_io.c
C
1#include <stdio.h>
2
3int main() {
4 // Read and echo characters until Enter
5 printf("Type something: ");
6 int ch;
7 while ((ch = getchar()) != '\n') {
8 putchar(ch); // Echo each character
9 }
10 putchar('\n');
11
12 // File character I/O
13 FILE *fp = fopen("test.txt", "r");
14 if (fp) {
15 while ((ch = fgetc(fp)) != EOF) {
16 putchar(ch); // Print file contents
17 }
18 fclose(fp);
19 }
20 return 0;
21}

05String I/O Functions

fgets() - Safe String Input ⭐

char *fgets(char *str, int n, FILE *stream);
str: Destination buffer
n: Max chars to read
stream: Input stream (stdin for console)
main.c
C
char name[50];
printf("Enter name: ");
fgets(name, sizeof(name), stdin); // Safe: won't overflow!
// Note: fgets includes the newline character

fputs() - Write String to Stream

int fputs(const char *str, FILE *stream);
main.c
C
fputs("Hello World!\n", stdout); // To console
FILE *fp = fopen("out.txt", "w");
fputs("Written to file", fp);
fclose(fp);

puts() - Simple String Output

int puts(const char *str);
main.c
C
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

FunctionPrototypeDescription
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
file_ops.c
C
1#include <stdio.h>
2
3int main() {
4 // Write to file
5 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 file
14 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

ModeDescriptionIf File ExistsIf Not Exists
"r"ReadOpenError (NULL)
"w"WriteTruncate (empty)Create
"a"AppendOpen at endCreate
"r+"Read/WriteOpenError
"w+"Read/WriteTruncateCreate
"rb"Read binaryAdd 'b' for binary mode

08Standard Streams

stdin

Standard Input (keyboard)

stdout

Standard Output (console)

stderr

Standard Error (errors)

09Summary

🎯 Key Functions

Output:

printf, fprintf, sprintf, snprintf

Input:

scanf, fscanf, sscanf, fgets

Character:

getchar, putchar, fgetc, fputc

File:

fopen, fclose, fread, fwrite

08Next Steps

Explore more C standard libraries: