Moonlit
Moonlit

Reputation: 5409

read user input without maxsize in C

In C i can use the char *fgets(char *s, int size, FILE *stream) function to read user input from stdin. But the size of the user input is limited to size. How can i read user input of variable size?

Upvotes: 1

Views: 155

Answers (2)

Lee Elenbaas
Lee Elenbaas

Reputation: 138

In C you are responsible for your buffers, and responsible for their size. So you can not have some dynamic buffer ready for you. So the only solution is to use a loop (either of fgets or fgetc - depends on your processing and on your stop condition)

If you go beyond C to C++, you will find that you can accept std::string objects of variable sizes (there you need to deal with word and/or line termination instead - and loop again)

Upvotes: 1

user529758
user529758

Reputation:

This function reads from standard input until end-of-file is encountered, and returns the number of characters read. It should be fairly easy to modify it to read exactly one line, or alike.

ssize_t read_from_stdin(char **s)
{
    char buf[1024];
    char *p;
    char *tmp;

    ssize_t total;
    size_t len;
    size_t allocsize;

    if (s == NULL) {
        return -1;
    }

    total = 0;

    allocsize = 1024;
    p = malloc(allocsize);
    if (p == NULL) {
        *s = NULL;
        return -1;
    }

    while(fgets(buf, sizeof(buf), stdin) != NULL) {
        len = strlen(buf);

        if (total + len >= allocsize) {
            allocsize <<= 1;
            tmp = realloc(p, allocsize);
            if (tmp == NULL) {
                free(p);
                *s = NULL;
                return -1;
            }

            p = tmp;
        }

        memcpy(p + total, buf, len);
        total += len;
    }       

    p[total] = 0;
    *s = p;

    return total;
}

Upvotes: 1

Related Questions