HOME HTML EDITOR C JAVA PHP

C stdio.h: Standard Input and Output

The <stdio.h> header stands for Standard Input Output. It contains the definitions of constants, macros, and functions used for performing input and output operations, such as reading from the keyboard or printing to the screen.

1. Core Concepts: Streams

In C, all input and output is dealt with through Streams. A stream is a logical interface to a file or a physical device.

2. Output Functions

These functions are used to send data from the program to the output device.

Function Purpose
printf() Prints formatted string to stdout.
putchar() Prints a single character.
puts() Prints a string followed by a newline (\n).

3. Input Functions

These functions are used to read data from the user or a device into the program.

char name[50];
int age;

printf("Enter age: ");
scanf("%d", &age); // Reads an integer

printf("Enter name: ");
fgets(name, 50, stdin); // Safer way to read strings with spaces

4. Formatting Specifiers

To print different types of data with printf or read with scanf, we use Format Specifiers.

5. File Operations in stdio.h

Beyond the console, stdio.h is used to manage files on the disk. It uses a FILE pointer to track the state of a file stream.

FILE *fptr;
fptr = fopen("example.txt", "w"); // Open for writing

if (fptr != NULL) {
    fprintf(fptr, "Hello File!");
    fclose(fptr);
}

6. Buffer Flushing

Sometimes, output is stored in a temporary memory called a "buffer" and not displayed immediately. The fflush() function can be used to force the transfer of data to the device.

fflush(stdout); // Forces anything in the output buffer to be printed
Pro Tip: Always check the return value of scanf(). It returns the number of items successfully read. If it returns 0, it means the user entered data that didn't match the format you expected!