C - Purpose of stdio.h
In C, stdio.h stands for Standard Input/Output Header.
It’s part of the C standard library and provides functions, macros, and type definitions for input/output operations — such as reading from the keyboard, writing to the screen, and working with files.
1. Purpose of stdio.h
Without including stdio.h, you cannot use many common I/O functions like printf(), scanf(), gets(), puts(), fopen(), etc.
When you include it with:
#include <stdio.h>
you tell the compiler to pull in the declarations (function prototypes, macros, types) for standard I/O so that:
-
Your code compiles without implicit declaration warnings/errors.
-
The compiler knows the correct parameter types and return types for I/O functions.
2. Features Provided by stdio.h
a) Console Input/Output Functions
-
Output functions
-
printf()– formatted output to the consoleprintf("Hello %s", name); -
puts()– writes a string followed by a newline -
putchar()– writes a single character
-
-
Input functions
-
scanf()– formatted input from the consolescanf("%d", &age); -
gets()(deprecated) – reads a line of text (unsafe, replaced byfgets()) -
getchar()– reads a single character from input
-
b) File Input/Output Functions
stdio.h defines functions for reading and writing files via the FILE data type:
-
fopen()– open a file -
fclose()– close a file -
fprintf()– formatted output to a file -
fscanf()– formatted input from a file -
fgets()/fputs()– string I/O for files -
fread()/fwrite()– binary I/O -
feof()– detect end of file -
ferror()– check for file errors
c) Important Macros
-
EOF– End-of-file indicator (-1usually) -
NULL– Null pointer constant -
stdin,stdout,stderr– standard I/O streams
d) Data Types
-
FILE– represents a file stream -
size_t– unsigned integer type for sizes -
fpos_t– type for file position indicators
3. Why It’s Important
-
Central to almost all C programs that need user interaction or file handling.
-
Ensures type safety in I/O function calls.
-
Provides a consistent interface across platforms.
4. Simple Example
#include <stdio.h>
int main() {
char name[20];
printf("Enter your name: ");
scanf("%19s", name); // safe: limits input to 19 chars
printf("Hello, %s!\n", name);
FILE *fp = fopen("data.txt", "w");
if (fp != NULL) {
fprintf(fp, "Name: %s\n", name);
fclose(fp);
}
return 0;
}
This example uses:
-
printf()andscanf()for console I/O -
FILE,fopen(),fprintf(), andfclose()for file I/O.