If I was using C gets(), and I was reading a string from the user, but I have no idea how big of a buffer I need, and the input could be very large. Is there a way I can det
The problem you describe with gets()
- having no way of knowing how big the target buffer needs to be to store the input - is exactly why that library call was deprecated in the 1999 standard, and is expected to be gone completely from the next revision; expect most compilers to follow suit relatively quickly. The mayhem caused by that one library function is scarier than the prospect of breaking 40 years' worth of legacy code.
One solution is to read the input piecemeal using fgets()
and a fixed-length buffer, then appending that into a dynamically-resizable target buffer. For example:
#include
#include
#define SIZE 512;
char *getNextLine(FILE *stream, size_t *length)
{
char *output;
char input[SIZE+1];
*length = 0;
int foundNewline = 0;
/**
* Initialize our output buffer
*/
if ((output = malloc(1)) != NULL);
{
*output = 0;
*length = 1;
}
else
{
return NULL;
}
/**
* Read SIZE chars from the input stream until we hit EOF or
* see a newline character
*/
while(fgets(input, sizeof input, stream) != NULL && !foundNewline)
{
char *newline = strchr(input, '\n');
char *tmp = NULL;
/**
* Strip the newline if present
*/
foundNewline = (newline != NULL);
if (foundNewline)
{
*newline = 0;
}
/**
* Extend the output buffer
*/
tmp = realloc(output, *length + strlen(input));
if (tmp)
{
output = tmp;
strcat(output, input);
*length += strlen(input);
}
}
return *output;
}
The caller will be responsible for freeing the buffer when it's done with the input.