getline not declared in this scope despite importing stdio

a 夏天 提交于 2019-12-11 02:46:46

问题


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 including features.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 it

  • You're not passing line by reference, since the function prototype is: ssize_t getline(char **lineptr, size_t *n, FILE *stream); hence char **lineptr



来源:https://stackoverflow.com/questions/20335695/getline-not-declared-in-this-scope-despite-importing-stdio

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!