Capturing a variable length string from the command-line in C

后端 未结 4 1621
耶瑟儿~
耶瑟儿~ 2021-01-16 06:03

I\'ve looked everywhere for an answer to my question, but I have yet to find a solid answer to my problem.

I\'m currently in the process of writing a program in C, s

4条回答
  •  既然无缘
    2021-01-16 06:19

    If you are using a gnu system, use the gnu getline extension to the c library, it does all the dynamic sizing for you.

    e.g. (though I haven't tested)

    void get_command()
    {
        /*
         * Reads in a command from the user, outputting the correct response
         */
    
        size_t buffer_size = 0;   
        char *command = NULL;
    
        ssize_t len = getline(&command, &buffer_size, stdin);
    
        if(len < 0)
        {
            perror("Error reading input");
        }
        else if (command[len - 1] == '\n')
        {
            puts("It's inside the buffer.");
        }
        else
        {
            puts("It's not inside the buffer.");
        }
    
        free(command);
    }
    

提交回复
热议问题