The fscanf function is an input function in C language, used to read data from files in a specified format. Its usage is as follows:
int fscanf(FILE *stream, const char *format, ...)
stream: The file pointer to be read can be the standard input stream stdin, a file pointer, or other open file streams.
format: Format control string, specifying the format and order of the data to be read.
...: Variable parameter list, used to receive read data.
The fscanf function works similarly to the scanf function, except that fscanf reads data from a file, while scanf reads data from the standard input stream. It reads the data in the file according to the specified format according to the format specifier in the format control string, and stores the read data into the corresponding parameters.
The following is a simple example demonstrating the usage of the fscanf function:
#include int main() { FILE *file; int num1, num2; // 打开文件 file = fopen("data.txt", "r"); // 从文件中读取两个整数 fscanf(file, "%d %d", &num1, &num2); // 输出读取的结果 printf("num1: %d\n", num1); printf("num2: %d\n", num2); // 关闭文件 fclose(file); return 0; }
In the above example, we opened a file named "data.txt" and copied the file from Read two integers. Format control string "%d %d" specifies that two integers are separated by a space. The read results are stored in the variables num1 and num2 and output through the printf function.
It should be noted that the fscanf function returns a successful match and reads The number of parameters taken. If the return value is less than the number of parameters, it may mean that the data in the file has been read or a reading error occurred. Therefore, when using the fscanf function, error handling needs to be performed based on the return value.
In summary, the fscanf function is a function used to read data from a file in a specified format. By controlling the format string and parameter list, the data in the file can be flexibly read and processed.
The above is the detailed content of Introduction to the usage of fscanf function. For more information, please follow other related articles on the PHP Chinese website!