How do you read the second line using the fgets function in C language?

To read the second line, you can call the fgets function to read the first line and ignore it before calling the fgets function again to read the second line.

Here is an example code:

#include <stdio.h>

int main() {
    FILE *file = fopen("file.txt", "r"); // 打开要读取的文件
    if (file == NULL) {
        printf("无法打开文件\n");
        return 1;
    }
    
    char line[100];
    
    // 读取并忽略第一行
    fgets(line, sizeof(line), file);
    
    // 读取第二行
    if (fgets(line, sizeof(line), file) != NULL) {
        printf("第二行内容:%s", line);
    } else {
        printf("无法读取第二行\n");
    }
    
    fclose(file); // 关闭文件
    
    return 0;
}

In the code above, we are using the fgets function to read each line of a file. We first open the file, then read and ignore the first line, and finally read and print the content of the second line. It is important to note that the file must be opened in read-only mode (“r”).

If your file is not a text file but a binary file, you can use the fread function to read a specific number of bytes of data.

bannerAds