[英]What is the purpose of the second parameter in getline?
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char* buffer = malloc(100 * sizeof(char));
size_t n = 3;
getline(&buffer, &n, stdin);
printf("%s\n", buffer);
free(buffer);
}
I thought the second parameter in getline
, size_t *n
, was to limit the number of characters read. 我认为
getline
的第二个参数size_t *n
是限制读取的字符数。 But when I tried with larger input, it still read all the input. 但是当我尝试使用更大的输入时,它仍然会读取所有输入。 I searched in the man pages and online but could not find an answer.
我在手册页和网上搜索但找不到答案。 Could anyone explain it for me?
有谁可以帮我解释一下?
From getline
man pages : 来自
getline
手册页 :
Given ssize_t getline(char **lineptr, size_t *n, FILE *stream);
给定
ssize_t getline(char **lineptr, size_t *n, FILE *stream);
If *lineptr is NULL, then getline() will allocate a buffer for storing the line, which should be freed by the user program.
如果* lineptr为NULL,则getline()将分配用于存储该行的缓冲区,该缓冲区应由用户程序释放。 (In this case, the value in *n is ignored.)
(在这种情况下,忽略* n中的值。)
Alternatively, before calling getline(), *lineptr can contain a pointer to a malloc(3)-allocated buffer *n bytes in size.
或者,在调用getline()之前,* lineptr可以包含指向malloc(3)分配缓冲区* n字节大小的指针。 If the buffer is not large enough to hold the line, getline() resizes it with realloc(3), updating *lineptr and *n as necessary.
如果缓冲区不足以容纳该行,则getline()使用realloc(3)调整其大小,根据需要更新* lineptr和* n。
Emphasis mine. 强调我的。 In short,
n
is updated to make sure the line fits. 简而言之,更新
n
以确保线条适合。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.