C - Formatted Library Functions

Formatted library functions in C are functions that allow you to perform input and output operations with formatted data. These functions are part of the standard C library and are declared in the header file. Formatted functions are used to read and write data with specific formatting, which includes specifying the type and structure of data. Here are some commonly used formatted library functions in C:

1. Formatted Output Functions:
  • 'printf': Used for formatted output to the standard output (usually the console). It allows you to specify formatting directives to control how data is printed.

#include <stdio.h>

int main() {
    int num = 42;
    printf("The value of num is %d.\n", num);
    return 0;
}

Output:


The value of num is 42.
2. Formatted Input Functions:
  • 'scanf': Used for formatted input from the standard input (usually the keyboard). It allows you to specify format specifiers to read data of specific types.

#include <stdio.h>

int main() {
    int num;
    printf("Enter an integer: ");
    scanf("%d", &num);
    printf("You entered: %d\n", num);
    return 0;
}

Output (console, user input):


Enter an integer: 123
You entered: 123
3. Formatted File I/O Functions:
  • 'fprintf': Used for formatted output to a specified file stream. It works similarly to printf but writes to a file.
  • 'fscanf': Used for formatted input from a specified file stream. It works similarly to scanf but reads from a file.

#include <stdio.h>

int main() {
    FILE *file = fopen("data.txt", "w");
    if (file != NULL) {
        int num = 42;
        fprintf(file, "The value of num is %d.\n", num);
        fclose(file);
    }
    return 0;
}

Output (file "data.txt"):


The value of num is 42.

4. Format Specifiers:
  • Format specifiers are used with formatted input and output functions to specify the type of data being read or written. For example, %d is used for integers, %f for floating-point numbers, %s for strings, and so on.

These formatted library functions provide control over how data is processed and displayed, making it easier to work with structured data and formatted text in C programs.