是否有一个很好的替代FGETS? [英] Is there a good alternative to fgets?

查看:104
本文介绍了是否有一个很好的替代FGETS?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是一个年轻的计算机专业的学生,​​目前我有点困惑什么是最好的做法是读标准输入的字符串。我知道,有很多方法可以做到这一点,一些比其他更安全,等等...
我目前需要的是prevents缓冲区溢出并附加一个空终止符(\\ 0)的字符串末尾的功能。我发现的与fgets 作为真正有用的,但是......它停止与\\ n或EOF阅读!如果我想在时间的用户输入不止一个行吗?是否有一些其他的功能,可以帮助我这样做?
我很抱歉,如果这个问题似乎傻了一些你,但请理解我!
任何帮助将是AP preciated。


解决方案

 的#define INITALLOC 16 / * #chars initally alloced * /
STEP的#define 8 / * #chars由realloc的* /
INT函数getline(字符** dynline)
{
    INT I,C;
    size_t型nalloced; / * #chars目前alloced * /    如果((* dynline =的malloc(INITALLOC))== NULL)
        返回0;
    nalloced = INITALLOC;
    对于(I = 0;(C =的getchar())= EOF;!++ⅰ){
        / *缓冲区已满,要求更多的纪念品* /
        如果(我== nalloced)
            如果((* dynline = realloc的(* dynline,nalloced + = STEP))== NULL)
                返回0;
        / *存储新读取的字符* /
        (* dynline)[i] = C;
    }
    / *零终止字符串* /
    (* dynline)[我] ='\\ 0';    如果(C == EOF)
        返回0; / *上* EOF返回0 /
    返回1;
}

此功能动态分配内存,所以调用者需要免费的内存。 函数getline 成功返回0 EOF或衰竭,1。

I'm just a young computer science student, and currently I'm a bit confused about what is the best practice to read a string from stdin. I know that there are a lot of ways to do that, some safer than other, and so on... I'm currently in need of a function that prevents buffer overflow and appends a null terminator character (\0) to the end of the string. I found fgets really useful for that, but ... It stops reading with \n or EOF! What if I want the user to input more than one line at time? Are there some other function that can help me doing that? I'm sorry if this question can seem silly to some of you, but please, understand me! Any help would be appreciated.

解决方案

#define INITALLOC  16  /* #chars initally alloced */
#define STEP        8  /* #chars to realloc by */
int getline(char **dynline)
{
    int i, c;
    size_t nalloced;  /* #chars currently alloced */

    if ((*dynline = malloc(INITALLOC)) == NULL)
        return 0;
    nalloced = INITALLOC;
    for (i = 0; (c = getchar()) != EOF; ++i) {
        /* buffer is full, request more mem */
        if (i == nalloced)
            if ((*dynline = realloc(*dynline, nalloced += STEP)) == NULL)
                return 0;
        /* store the newly read character */
        (*dynline)[i] = c;
    }
    /* zero terminate the string */
    (*dynline)[i] = '\0';

    if (c == EOF)
        return 0;  /* return 0 on EOF */
    return 1;
}

This function allocates memory dynamically, so the caller needs to free the memory. getline returns 0 on EOF or failure, and 1 on success.

这篇关于是否有一个很好的替代FGETS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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