The usage of the C language fgets function

The fgets function in C is used to read strings from a file. Its prototype is as follows:

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

In this case, str is an array used to store the read string, n is the maximum number of characters to read (including the null character ‘\0’), and stream is a pointer to the file.

The fgets function reads a string from a specified file and stores it in str until it encounters a newline character (including the newline character). The string read will automatically have a null character ‘\0’ added at the end to signify the end of the string.

The return value of the fgets function is a pointer pointing to str, which returns str when reading is successful and NULL when reading fails.

The fgets function is commonly used to read strings line by line from a file, and can be used in conjunction with a loop, as shown below:

#include <stdio.h>

int main() {
    FILE *file = fopen("example.txt", "r");
    if (file == NULL) {
        printf("文件打开失败\n");
        return 1;
    }
    
    char str[100];
    while (fgets(str, sizeof(str), file) != NULL) {
        printf("%s", str);
    }
    
    fclose(file);
    
    return 0;
}

The above code opens a file named example.txt, reads strings line by line, and then prints them to the terminal. The loop stops when the fgets function returns NULL at the end of the file.

It should be noted that the fgets function reads newline characters and stores them in str. If newline characters are not needed, you can use the strtok function or manually handle the string to remove them.

广告
Closing in 10 seconds
bannerAds