C programming stdio.h function - int fscanf(FILE *stream, const char *format, ...)

h‮/:sptt‬/www.theitroad.com

The fscanf() function is used to read formatted data from a file. It is declared in the stdio.h header file.

The syntax for the fscanf() function is:

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

Here, stream is a pointer to the FILE object that specifies the input stream, and format is a string that contains one or more format specifiers, which determine the type of data to be read from the input stream.

The ... in the function signature indicates that the function can take a variable number of arguments, depending on the number of format specifiers in the format string.

The function returns the number of input items successfully matched and assigned, which can be fewer than the number of format specifiers in the format string if an input error occurs or if the end of the input stream is reached before all the format specifiers are matched.

Example usage:

FILE *fp;
int a, b;
float c;

fp = fopen("data.txt", "r");
if (fp == NULL) {
  printf("Error opening file.\n");
  return 1;
}

if (fscanf(fp, "%d,%d,%f", &a, &b, &c) == 3) {
  printf("Read values: %d, %d, %f\n", a, b, c);
} else {
  printf("Error reading values.\n");
}

fclose(fp);

In this example, the fscanf() function is used to read three values from a file named "data.txt" that are separated by commas. The values are stored in the variables a, b, and c. If the fscanf() function successfully reads three values, it prints them to the console. Otherwise, it prints an error message. Finally, the file is closed with the fclose() function.