fscanf() function in C++

In this guide, you will learn what is fscanf() function is in C++ programming and how to use it with an example.

1. fscanf() Function Overview

The fscanf() function is part of the <cstdio> library in C++. It allows for formatted input from a specified stream, typically used for reading formatted data from files. It's analogous to the scanf() function, but instead of reading from the standard input, it reads from a given file stream.

Signature:

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

Parameters:

- stream: Pointer to the file stream from which the formatted input should be read.

- format: A string that specifies how the subsequent arguments are interpreted during input.

- ...: Variable number of arguments that will store the values read from the stream according to the format string.

2. Source Code Example

#include <iostream>
#include <cstdio>

int main() {
    FILE* pFile = fopen("example.txt", "r");

    if (pFile == nullptr) {
        std::cerr << "Error opening file." << std::endl;
        return 1;
    }

    // Read formatted data from the file
    int age;
    char name[50];
    fscanf(pFile, "Name: %49s\nAge: %d", name, &age);

    // Close the file
    fclose(pFile);

    std::cout << "Read from the file: Name = " << name << ", Age = " << age << std::endl;

    return 0;
}

Output:

(Considering "example.txt" has the content:
Name: JohnDoe
Age: 25
)
Read from the file: Name = JohnDoe, Age = 25

3. Explanation

1. We first open a file named "example.txt" in read mode.

2. The fscanf() function is then used to read a formatted string from the pFile stream. The %s format specifier reads the string into name, and the %d format specifier reads the integer into age.

3. Finally, the file is closed using fclose().


Comments