getline中第二个参数的作用是什么?
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);
}
我以为getline
中的第二个参数,size_t *n
,是限制读取的字符数。但是当我尝试使用更大的输入时,它仍然读取所有输入。我在手册页和网上进行了搜索,但找不到答案。谁能帮我解释一下?
给定 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. (In this case,
the value in *n is ignored.)
Alternatively, before calling getline(), *lineptr can contain a
pointer to a malloc(3)-allocated buffer *n bytes in size. If the
buffer is not large enough to hold the line, getline() resizes it with
realloc(3), updating *lineptr and *n as necessary.
强调我的。简而言之,更新 n
以确保该行适合。
#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);
}
我以为getline
中的第二个参数,size_t *n
,是限制读取的字符数。但是当我尝试使用更大的输入时,它仍然读取所有输入。我在手册页和网上进行了搜索,但找不到答案。谁能帮我解释一下?
给定 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. (In this case, the value in *n is ignored.)
Alternatively, before calling getline(), *lineptr can contain a pointer to a malloc(3)-allocated buffer *n bytes in size. If the buffer is not large enough to hold the line, getline() resizes it with realloc(3), updating *lineptr and *n as necessary.
强调我的。简而言之,更新 n
以确保该行适合。