fscanf stops at space

Explanation of fscanf in C

In C programming, fscanf is a function used to read formatted input from a file. It is similar to scanf, but instead of reading input from the standard input (keyboard), it reads input from a file. The fscanf function takes the following parameters:

  • File pointer: A pointer to the file from which the input is to be read.
  • Format string: A string that specifies the format of the input to be read.
  • Variables: Pointers to the variables where the read values will be stored.

The fscanf function reads input from the file according to the format specified in the format string and stores the read values in the corresponding variables. It stops reading when it encounters a whitespace character (space, tab, newline) or when the specified format has been completely read.

Here's an example usage of fscanf:

#include <stdio.h>

int main() {
    FILE *file = fopen("input.txt", "r");
    int num1, num2;
    fscanf(file, "%d %d", &num1, &num2);
    printf("Read values: %d, %d\n", num1, num2);
    fclose(file);
    return 0;
}

In this example, fscanf reads two integers from the file "input.txt" and stores them in the variables num1 and num2. The format string "%d %d" specifies that two integers separated by a space should be read.

Please note that the fscanf function returns the number of successfully matched and assigned input items. It can be used to check if the reading was successful.