C 编程 - 使用文件处理函数移动到文本文件中的下一行

C Programming - Move to the next line in a text file using file handling functions

我有一个包含 4 个单词的文本文件;每一个都在一行中,哪个函数可以让我控制这些行;就像我只想阅读第一行然后移动到下一行(相当于控制台中的 \n )并将每一行存储在一个字符串中

有两个主要的逐行读取输入的函数:

  • 如果您有预分配缓冲区,请使用 fgets
  • 如果你想为你分配缓冲区,使用getline(注意它只符合POSIX 2008及以上)。

使用fgets

#include <stdio.h> // fgets
FILE *f = stdin;

char buf[4096]; // static buffer of some arbitrary size.
while (fgets(buf, sizeof(buf), f) == buf) {
    // If a newline is read, it would be at the end of the buffer. The newline may not be read if fgets() reaches the buffer limit, or if EOF is reached, or if reading the file is interrupted.
    printf("Text: %s\n", buf);
}

使用getline

#define _POSIX_SOURCE 200809L // getline is not standard ISO C, but rather part of POSIX.
#include <stdio.h> // getline
#include <stdlib.h> // free

FILE *f = stdin;
char *line = NULL;
size_t len = 0;
ssize_t nread;

while (nread = getline(&line, &len, f)) != 1) {
    // Note that the newline \n is always stored unless it reached EOF first.
    // len stores the current length of the buffer, and nread stores the length of the current string in the buffer. getline() grows the buffer for you whenever it needs to.
    printf("New line read: %s", line);
}

// It's the programmer's job to free() the buffer that getline() has allocated
free(line);