Dynamically allocate user inputted string

后端 未结 4 1379
不思量自难忘°
不思量自难忘° 2020-12-04 02:47

I am trying to write a function that does the following things:

  • Start an input loop, printing \'> \' each iteration.
  • Take whatever the
4条回答
  •  天命终不由人
    2020-12-04 03:24

    If you are on a POSIX system such as Linux, you should have access to getline. It can be made to behave like fgets, but if you start with a null pointer and a zero length, it will take care of memory allocation for you.

    You can use in in a loop like this:

    #include 
    #include 
    #include     // for strcmp
    
    int main(void)
    {
        char *line = NULL;
        size_t nline = 0;
    
        for (;;) {
            ptrdiff_t n;
    
            printf("> ");
    
            // read line, allocating as necessary
            n = getline(&line, &nline, stdin);
            if (n < 0) break;
    
            // remove trailing newline
            if (n && line[n - 1] == '\n') line[n - 1] = '\0';
    
            // do stuff
            printf("'%s'\n", line);
            if (strcmp("quit", line) == 0) break;
        }
    
        free(line);
        printf("\nBye\n");
    
        return 0;
    }
    

    The passed pointer and the length value must be consistent, so that getline can reallocate memory as required. (That means that you shouldn't change nline or the pointer line in the loop.) If the line fits, the same buffer is used in each pass through the loop, so that you have to free the line string only once, when you're done reading.

提交回复
热议问题