问题
I need to use getline()
in C, but when i write:
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char** argv) {
char *line;
getline(&line, NULL, stdin);
free(line);
return (0);
}
compiler writes error: getline was not declared in this scope
what can i do? Isn't getline is delared in stdio.h
? I never had this kind of problem before.
I use GCC GNU Compiler.
回答1:
You need to define _GNU_SOURCE
to use this function, either define it before the inclusion of stdio.h
or pass it to the compile as -D_GNU_SOURCE
since this is a GNU extension function.
Another possible cause is that your GLIBC does not have this function, so either try:
grepping for it in
/usr/include/stdio.h
Test for
_POSIX_C_SOURCE >= 200809L || _XOPEN_SOURCE >= 700
like the manual page says (after includingfeatures.h
)
The following implementation may work (Un-tested):
#define INTIAIL_SIZE 100
size_t getline(char **lineptr, size_t *n, FILE *stream)
{
char c;
size_t read = 0;
char *tmp;
if (!*lineptr) {
if (!n)
*n = INTIAIL_SIZE;
tmp = malloc(*n);
*lineptr = tmp;
} else
tmp = *lineptr;
while ((c = fgetc(stream)) != '\n') {
*tmp++ = c;
if (++read >= *n) {
char *r = realloc(tmp, *n * 2);
if (!r) {
errno = ENOMEM;
return -1;
} else
tmp = r;
}
}
*n = read;
return read;
}
Errors you currently have:
You're not freeing
line
after you've used itYou're not passing
line
by reference, since the function prototype is:ssize_t getline(char **lineptr, size_t *n, FILE *stream);
hencechar **lineptr
来源:https://stackoverflow.com/questions/20335695/getline-not-declared-in-this-scope-despite-importing-stdio