Home  >  Article  >  Backend Development  >  fgets() function - detailed explanation of reading the line pointed to by the file

fgets() function - detailed explanation of reading the line pointed to by the file

WBOY
WBOYOriginal
2023-06-27 09:06:281377browse

fgets() function is one of the functions in the C standard library used to read file pointed lines. Its characteristic is that it can read file data line by line. The read data is stored in the specified buffer and can be specified. The maximum length of read data. The fgets() function is usually used to read plain text files, such as reading data for each line in a text file.

The syntax of the fgets() function is as follows:

char *fgets(char *str, int n, FILE *stream)

Among them, str is the specified buffer to store the read data, n is the length of the specified maximum read data, and stream is the pointer to be read. Get the pointer to the file. The fgets() function reads a line of data from the specified file. The data is stored in the buffer str and returns a pointer to the buffer. If no data is read or an error occurs, NULL is returned.

The following is a sample program that demonstrates using the fgets() function to read the line pointed to by the file:

#include <stdio.h>

#define MAX_LEN 100 // 设置最大读取数据的长度

int main(void)
{
    char file_name[100], str[MAX_LEN];
    FILE *fp;

    printf("请输入文件名: ");
    fgets(file_name, sizeof(file_name), stdin);  // 从标准输入读取文件名

    if (fp = fopen(file_name, "r")) // 判断文件是否能够打开
    {
        while (fgets(str, MAX_LEN, fp) != NULL) // 循环读取文件每一行数据
        {
            printf("%s", str); // 输出读取的数据
        }
        fclose(fp); // 关闭文件
    }
    else
    {
        printf("无法打开指定的文件: %s", file_name);
    }

    return 0;
}

The above sample program will open the file name entered by the user, read the data in the file in a loop, and then Output the data for each row. After running the program, the user only needs to enter the file name to be read, and each line of data in the file can be output.

In short, with the help of the fgets() function, each line of data in the text file can be read quickly and accurately, which provides convenience for file processing. When using the fgets() function, be careful to prevent buffer overflow and normal operations such as closing files.

The above is the detailed content of fgets() function - detailed explanation of reading the line pointed to by the file. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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