What is vfscanf_s in C?

The vfscanf_s function

The function vfscanf_s is defined in the stdio.h standard library and is used to read data from a file stream. The structure of the vfscanf_s function is as follows:

int vfscanf_s(FILE * stream, const char * format, va_list arglist);

Parameters

  • stream is a pointer to a FILE structure.
  • format is a pointer to a character array which represents a format string.
  • arglist is a list of arguments required by the format string.

Return value

  • A positive number specifying the number of fields successfully read and assigned.
  • EOF if an error occurs or the end of the stream is reached.

Example usage of the vfscanf_s function

The following code demonstrates the use of the vfscanf_s function:

#include<stdio.h>
/*
call_vfscanf_s is a wrapper function which converts "..." to "arglist" and calls vfscanf_s function
*/
int call_vfscanf_s(FILE * stream, char * format, ...) {
int result;
va_list arglist;
va_start(arglist, format);
result = vfscanf_s(stream, format, arglist);
va_end(arglist);
return result;
}
int main() {
char text[10];
int score_obtained;
int total_score;
/*
Contents of file "temp.txt":
Score: 8 10
*/
FILE * stream = fopen("temp.txt", "r");
call_vfscanf_s(stream, "%s %d %d", &text, &score_obtained, &total_score);
fclose(stream);
printf("Score Obtained: %d\n", score_obtained);
printf("Total Score: %d\n", total_score);
return 0;
}

Output:

Score Obtained: 8
Total Score: 10

In the example above, a file temp.txt is read using the function vfscanf_s by opening a file stream in line 23. The result of the file is stored in 3 variables: text, score_obtained, and total_score, as specified by the format string %s %d %d and the order of the said 3 variables passed to the call_vfscanf_s function. The variables text, score_obtained, and total_score stored Score:, 8, and 10 respectively. Finally, the score_obtained and the total_score were printed onto the standard output.

Note: The function above is not supported by the GCC compiler, so you will get an implicit declaration of function… error.

Use the following function vfscanf to get the job done:

int vfscanf(FILE * stream, const char * format, va_list arglist);

All parameters and return values are the same as the vfscanf_s function.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved