从C中的命令行捕获可变长度字符串

Zac*_*ura 1 c stdin

我到处寻找我的问题的答案,但我还没有找到一个可靠的答案来解决我的问题.

我目前正在用C编写程序,专门针对UNIX命令行(我使用Linux作为我的开发环境,但我希望这个程序尽可能便携).现在,我有一个提示用户输入的基本shell.然后,用户将输入命令,并相应地处理该命令.这是我到目前为止的代码:

/* Main.c */
int main(int argc, char **argv)
{
    while (TRUE)
    {
        display_prompt();
        get_command();
    }

    return 0;
}

/* Main.h */
void get_command()
{
    /*
     * Reads in a command from the user, outputting the correct response
     */

    int buffer_size = 20;   
    char *command = (char*) malloc(sizeof(char) * buffer_size);

    if (command == NULL)
    {
       return_error("Error allocating memory");
    }

    fgets(command, buffer_size, stdin);
    if (command[strlen(command) - 1] == '\n')
    {
        puts("It's inside the buffer.");
    }
    else
    {
        puts("It's not inside the buffer.");
    }

    free(command);
}
Run Code Online (Sandbox Code Playgroud)

我最初的想法是检查\n字符并查看它是否适合buffer_size,如果它没有realloc()扩展分配的内存的数据.

但是,在realloc()我的字符串之后,我将如何将剩余数据添加stdincommand

Jo *_* So 5

如果你真的需要,请使用getline(3).这是POSIX.1-2008.请注意,无限长度行是DOS攻击(OOM)的简单攻击向量.因此,考虑制定合理的行长度限制,并使用fgets(3).