fgets is a C language standard library function, which is used to read a line of data from the specified stream until the specified maximum number of characters is reached, or a newline character or EOF (End Of File, end of file flag) is encountered. .
The function prototype is as follows:
char *fgets(char *str, int n, FILE *stream);
Parameter explanation:
str: This is a pointer to a character array, fgets will put the read string into this array .
n: This is the maximum number of characters to read (including the null character '\0').
stream: This is the input stream to be read.
The fgets function returns a pointer to str. If the read fails or EOF is encountered, it returns NULL.
The following is a simple example showing how to use the fgets function to read data from a file:
#include <stdio.h> int main() { FILE *file = fopen("example.txt", "r"); if (file == NULL) { printf("Failed to open file\n"); return 1; } char buffer[100]; while (fgets(buffer, 100, file) != NULL) { printf("%s", buffer); } fclose(file); return 0; }
In this example, we open a file named "example.txt", And use the fgets function to read each line of data from the file until EOF is encountered. Each line of data is stored in the buffer and printed immediately.
The above is the detailed content of How to use fgets function. For more information, please follow other related articles on the PHP Chinese website!