从文件中读取行

stdio.h 标头定义了 fgets() 功能。此函数从流中读取一行并将其存储在指定的字符串中。当读取 n - 1 字符,读取换行符('\n')或到达文件结尾(EOF)时,该函数停止从流中读取文本。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_LINE_LENGTH 80

int main(int argc, char **argv)
{
    char *path;
    char line[MAX_LINE_LENGTH] = {0};
    unsigned int line_count = 0;
    
    if (argc < 1)
        return EXIT_FAILURE;
    path = argv[1];
    
    /* Open file */
    FILE *file = fopen(path, "r");
    
    if (!file)
    {
        perror(path);
        return EXIT_FAILURE;
    }
    
    /* Get each line until there are none left */
    while (fgets(line, MAX_LINE_LENGTH, file))
    {
        /* Print each line */
        printf("line[%06d]: %s", ++line_count, line);
        
        /* Add a trailing newline to lines that don't already have one */
        if (line[strlen(line) - 1] != '\n')
            printf("\n");
    }
    
    /* Close file */
    if (fclose(file))
    {
        return EXIT_FAILURE;
        perror(path);
    }
}

使用参数调用程序,该参数是包含以下文本的文件的路径:

This is a file
  which has
multiple lines
    with various indentation,
blank lines

a really long line to show that the line will be counted as two lines if the length of a line is too long to fit in the buffer it has been given,
  and punctuation at the end of the lines.

将导致以下输出:

line[000001]: This is a file
line[000002]:   which has
line[000003]: multiple lines
line[000004]:     with various indentation,
line[000005]: blank lines
line[000006]: 
line[000007]: 
line[000008]: 
line[000009]: a really long line to show that the line will be counted as two lines if the le
line[000010]: ngth of a line is too long to fit in the buffer it has been given,
line[000011]:  and punctuation at the end of the lines.
line[000012]: 

这个非常简单的例子允许固定的最大线长度,这样较长的线将有效地计为两条线。fgets() 函数要求调用代码提供用作读取行的目标的内存。

POSIX 使 getline() 功能可用,而是在内部分配内存以根据需要扩展任何长度的行(只要有足够的内存)。