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



我有一个包含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: %sn", 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);

最新更新