且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

是否有一个很好的替代FGETS?

更新时间:2023-02-11 19:21:28

 的#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.