Is it possible to pull one line at a time from a stream without specifying the buffer size (unlike in fgets)? Also, is there any way to store that line into a char*? Thanks.
Is it possible to pull one line at a time from a stream without specifying the buffer size (unlike in fgets)? Also, is there any way to store that line into a char*? Thanks.
You write your own function which just calls fgetc() in a loop, and you keep allocating space with say malloc until you read the newline or the end of memory.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
The only method I know of continually reallocates memory to a char* while adding the character to the last element. Personally, I want to avoid realloc if possible. Has anyone written a function which does this and wouldn't mind posting it?
std::string or std::vector? Or is C++ not an option?Originally Posted by Queue
7. It is easier to write an incorrect program than understand a correct one.
40. There are two ways to write error-free programs; only the third one works.*
>The only method I know of continually reallocates memory to a char* while adding the character to the last element.
Yep, that's about all there is to it.
>Personally, I want to avoid realloc if possible.
Then use malloc and strcpy. If you don't want to specify a size, you need to let your string grow, and that means dynamic allocation.
>Has anyone written a function which does this and wouldn't mind posting it?
Yes. In fact, this particular problem comes up regularly and several of our top minds come up with something different each time. I think I've posted a dozen or so variations of such a function over the years. Search is your friend.
My best code is written with the delete key.
Unfortunately, the reading must be in C to keep it consistent with the rest of the program. Prelude's post answered my question completely. Thanks everyone for all the help.Originally Posted by Dave_Sinkula