Purpose of the fscanf Function in C programming

Purpose of the <code>fscanf</code> Function in C

Purpose of the fscanf Function in C

The fscanf function in C is used for formatted input. It reads data from a file or standard input and parses it according to a specified format. This function is similar to scanf, but instead of reading from the standard input (keyboard), it reads from a file or other input stream.

Syntax

The syntax for fscanf is as follows:

int fscanf(FILE *stream, const char *format, ...);

Where:

  • stream is a pointer to a FILE object that identifies the input stream (e.g., a file).
  • format is the format string that specifies how the input data should be parsed.
  • ... represents additional pointers to variables where the parsed data will be stored.

Example Code

#include <stdio.h>

int main() {
    FILE *file = fopen("data.txt", "r");
    int age;
    float height;

    if (file != NULL) {
        fscanf(file, "%d %f", &age, &height);
        fclose(file);

        printf("Age: %d\n", age);
        printf("Height: %.2f\n", height);
    } else {
        printf("Error opening file.\n");
    }

    return 0;
}

In this example:

  • FILE *file = fopen("data.txt", "r"); opens a file named data.txt for reading.
  • fscanf(file, "%d %f", &age, &height); reads an integer and a floating-point number from the file and stores them in the age and height variables, respectively.
  • fclose(file); closes the file after reading.
  • printf("Age: %d\n", age); and printf("Height: %.2f\n", height); print the values of age and height to the standard output.

Key Points

  • File Input: fscanf can read formatted data from files or standard input streams.
  • Format Specifiers: Use format specifiers in the format string to parse different types of data (e.g., %d for integers, %f for floating-point numbers).
  • Error Handling: Always check if the file was successfully opened before using fscanf, and handle potential read errors appropriately.
Note: Be cautious with fscanf as improper format specifiers or mismatched data types can lead to unexpected behavior or errors.

Comments

Popular Posts