函数getline不在此范围内,尽管进口申报标准输入输出 [英] getline not declared in this scope despite importing stdio

查看:376
本文介绍了函数getline不在此范围内,尽管进口申报标准输入输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用函数getline()当我写在C,但:

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);
}

编译器写入错误:函数getline不是在这个范围内声明我能做些什么?是不是函数getline在 stdio.h中 delared?我从未有过这样的问题了。

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.

我用GCC GNU编译器。

I use GCC GNU Compiler.

推荐答案

您需要定义 _GNU_SOURCE 列入前使用此功能时,无论是把它定义 stdio.h中或将它传递给编译为 -D_GNU_SOURCE ,因为这是一个GNU的扩展功能。

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.

另一个可能的原因是,你的glibc没有这个功能,所以可尝试:

Another possible cause is that your GLIBC does not have this function, so either try:


  • 在grepping它 /usr/include/stdio.h

_POSIX_C_SOURCE&GT测试_XOPEN_SOURCE&GT; = 700 像手册说(包括后 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;
}

错误您目前有:


  • 您不是释放您已经使用后,

你不及格引用,因为函数原型为: ssize_t供函数getline(字符** lineptr,为size_t * N,FILE *流); 因此,的char ** lineptr

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

这篇关于函数getline不在此范围内,尽管进口申报标准输入输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆