C stdio.h Header

Standard Input/Output operations in C

📄 What is stdio.h?

The stdio.h header provides functions for input and output operations. It includes printf for displaying text, scanf for reading input, and file handling functions for working with files.


#include <stdio.h>

int main() {
    printf("Hello, World!\n");
    return 0;
}
                                    

Output:

Hello, World!

Key stdio.h Functions

📝

printf()

Display formatted output to screen

printf("Age: %d\n", 25);
⌨️

scanf()

Read formatted input from user

scanf("%d", &age);
📁

fopen()

Open files for reading/writing

FILE *fp = fopen("data.txt", "r");
🔤

getchar()

Read single character from input

char ch = getchar();

🔹 Basic Input/Output Example

Standard input and output operations in C use functions from the stdio.h library for reading and writing data. The printf() function displays formatted output to the console, supporting format specifiers like %d for integers, %f for floating-point numbers, and %s for strings. Conversely, scanf() reads formatted input from the user, storing values in variables through pointer references. For example, scanf("%d", &number); reads an integer from standard input and stores it in the number variable. These fundamental I/O operations form the basis for interactive programs and user communication in C applications.

#include <stdio.h>

int main() {
    char name[50];
    int age;
    
    printf("Enter your name: ");
    scanf("%s", name);
    
    printf("Enter your age: ");
    scanf("%d", &age);
    
    printf("Hello %s, you are %d years old!\n", name, age);
    
    return 0;
}

Sample Output:

Enter your name: John
Enter your age: 25
Hello John, you are 25 years old!

🔹 File Operations

File operations in C provide comprehensive capabilities for reading from and writing to files using the stdio.h library. The fopen() function opens a file with specified modes like "r" for reading, "w" for writing, or "a" for appending, returning a FILE pointer for subsequent operations. Functions like fprintf(), fscanf(), fgets(), and fputs() enable formatted and line-based file I/O operations. Always check if fopen() returns NULL to detect file opening errors, and remember to call fclose() to properly release file resources and flush any buffered data to disk, preventing data loss and resource leaks.

#include <stdio.h>

int main() {
    FILE *file;
    char text[100];
    
    // Write to file
    file = fopen("example.txt", "w");
    fprintf(file, "Hello File!\n");
    fclose(file);
    
    // Read from file
    file = fopen("example.txt", "r");
    fgets(text, 100, file);
    printf("File content: %s", text);
    fclose(file);
    
    return 0;
}

Output:

File content: Hello File!

🧠 Test Your Knowledge

Which function is used to display output in C?