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,612
  • 10
  • 26
  • 42
nerdguy
  • 174
  • 1
  • 16

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
  • 106,608
  • 13
  • 126
  • 198