Is it possible to read in a string of unknown size in C, without having to put it in a pre-allocated fixed length buffer?
c
Solution
At the point that you read the data, your buffer is going to have a fixed size -- that's unavoidable.
What you can do, however, is read the data using fgets, and check whether the last character is a '\n', (or you've reached the end of file) and if not, `realloc` your buffer, and read more.
I rarely find that necessary, but do usually allocate a single fixed buffer for the reading, read data into it, and then dynamically allocate space for a copy of it, allocating only as much space as it actually occupies, not the whole size of the buffer I originally used.
Problem
Is it possible to read in a string in C, without allocating an array of fixed size ahead of time? Everytime I declare a char array of some fixed size, I feel like I'm doing it wrong. I'm always taking a guess at what I think would be the maximum for my usecase, but this isn't always easy. Also, I don't like the idea of having a smaller string sitting in a larger container. It doesn't feel right. Am I missing something? Is there some other way I should be doing this?