0

I have been trying to learn C, and was wondering: how would one get a string with an unknown length in C? I have found some results, but am not sure how to apply them.

Pika Supports Ukraine
  • 3,394
  • 9
  • 24
  • 41
nerdguy
  • 165
  • 1
  • 15

1 Answers1

0

If you're ok with extensions to the Standard, try POSIX getline().

Example from documentation:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    FILE *fp;
    char *line = NULL;
    size_t len = 0;
    ssize_t read;
    fp = fopen("/etc/motd", "r");
    if (fp == NULL)
        exit(1);
    while ((read = getline(&line, &len, fp)) != -1) {
        printf("Retrieved line of length %zu :\n", read);
        printf("%s", line);
    }
    if (ferror(fp)) {
        /* handle error */
    }
    free(line);
    fclose(fp);
    return 0;
}
pmg
  • 103,426
  • 11
  • 122
  • 196