Skip to content
On this page

getline()


标签:linux/api  

在 C 语言的库中,没有一个函数可以实现对一行数据的读取,这是因为我们不能够知道一行数据的实际大小是多少,程序应该申请多大的空间。

但如果要设计一个读取一行的函数,我们可能需先申请空间,当空间不够的时候逐步使用 realloc 来扩展空间的大小。

在 GNU 里有 getline() 这个函数实现了上述的功能。

函数原型

c
#include <stdio.h>
ssize_t getline(char **lineptr, size_t *n, FILE *stream);

第一个参数是指针的指针,实际上就是 char 数组指针,n 是这个指针空间的字节大小。这个指针指向的空间如果是 NULL 而且 n 为 0,getline 会帮助用户申请空间(但是需要自己释放),但也可以自己申请固定长度的空间。

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

int main() {
  char *buffer;
  size_t bufsize = 32;
  size_t characters;

  buffer = (char *)malloc(bufsize * sizeof(char));
  if(buffer == NULL) {
    perror("Unable to allocate buffer");
    exit(1);
  }

  printf("Type something: ");
  characters = getline(&buffer, &bufsize, stdin);
  printf("%zu characters were read.\n", characters);
  printf("You typed: %sNextLine.\n", buffer);

  return (0);
}
txt
Type something: hello world
12 characters were read.
You typed: hello world
NextLine.
  • 自带行换

在它的 man 手册中,有一段示例代码:

c
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>

int
main(int argc, char *argv[])
{
   FILE *stream;
   char *line = NULL;
   size_t len = 0;
   ssize_t nread;

   if (argc != 2) {
	   fprintf(stderr, "Usage: %s <file>\n", argv[0]);
	   exit(EXIT_FAILURE);
   }

   stream = fopen(argv[1], "r");
   if (stream == NULL) {
	   perror("fopen");
	   exit(EXIT_FAILURE);
   }

   while ((nread = getline(&line, &len, stream)) != -1) {
	   printf("Retrieved line of length %zd:\n", nread);
	   fwrite(line, nread, 1, stdout);
   }

   free(line);
   fclose(stream);
   exit(EXIT_SUCCESS);
}

Last updated: