How to use fgets function

小老鼠
Release: 2023-11-28 10:51:16
Original
3604 people have browsed it

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);
Copy after login

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  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; }
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!