C stdio.h Library: Essential Functions for Input and Output
The <stdio.h> library in C is crucial for handling input and output operations. It includes a variety of functions for reading from and writing to files, managing user input, and formatted string handling, making it fundamental for performing I/O tasks in C programming.
C stdio.h Library
The <stdio.h> header provides various functions for handling input and output operations, including reading from and writing to files, managing user input, and formatted string handling. These functions are fundamental for performing I/O tasks in C.
Common C stdio Functions
Here is a list of some common functions provided by the stdio.h library along with their descriptions:
| Function | Description | 
|---|---|
| fclose() | Closes a file. | 
| feof() | Returns true when the file pointer reaches the end of the file. | 
| ferror() | Returns true if a file operation encounters an error. | 
| fgetc() | Reads and returns the next character from a file. | 
| fgets() | Reads a line of text from a file. | 
| fopen() | Opens a file and returns a pointer for file operations. | 
| fprintf() | Writes a formatted string to a file. | 
| fputc() | Writes a character to a file. | 
| fputs() | Writes a string to a file. | 
| fread() | Reads data from a file into a block of memory. | 
| fwrite() | Writes data from memory to a file. | 
| getc() | Equivalent to fgetc(). | 
| getchar() | Reads a single character from user input. | 
| printf() | Prints a formatted string to the console. | 
| putchar() | Writes a character to the console. | 
| puts() | Outputs a string to the console. | 
| remove() | Deletes a file. | 
| rename() | Renames a file. | 
| scanf() | Reads formatted input from the user. | 
| sprintf() | Writes a formatted string into a char array. | 
Example: Basic File Operations
Let's take a look at an example that demonstrates file operations using stdio.h. The program opens a file, writes to it, and then reads the content back:
Example: Writing to and Reading from a File
#include <stdio.h>
int main() {
    FILE *filePointer;
    
    // Open a file in write mode
    filePointer = fopen("example.txt", "w");
    if (filePointer == NULL) {
        printf("Error opening file!\n");
        return 1;
    }
    // Write to the file
    fprintf(filePointer, "Hello, File!\n");
    
    // Close the file
    fclose(filePointer);
    // Open the file in read mode
    filePointer = fopen("example.txt", "r");
    if (filePointer == NULL) {
        printf("Error opening file!\n");
        return 1;
    }
    // Read from the file and print to console
    char line[100];
    fgets(line, sizeof(line), filePointer);
    printf("File content: %s", line);
    
    // Close the file
    fclose(filePointer);
    return 0;
}
Output:
Output
File content: Hello, File!
This program creates a file named example.txt, writes "Hello, File!" into it, and then reads the content back from the file, printing it to the console.