Originally Posted by
MK27
Where did you put all the characters you fgot before the newline?
Eh? if NORMAL behaviour is relative short lines, then you can deal with the problem in this way:
Code:
while(fgets(str, ...) != NULL)
{
if (strrchr(str, '\n') == NULL)
{
// didn't get a whole line.
int ch;
printf("Very long line, skipping it.\n");
while((ch = fgetc(...)) != '\n' && ch != EOF) ;
}
}
If you EXPECT to get very long lines [or at least can sort of guess that it MAY happen], then you may need to deal with arbitrary length lines and have to gather it all up in one big lump, something like this:
Code:
int uselongline = 0;
char *longline = NULL;
while(fgets(str, ...) != NULL)
{
char *newline = strrchr(str, '\n');
if (newline || uselongline)
{
longline = realloc(verylongline, strlen(longline) + strlen(str) + 1);
strncat(longline, str);
if (newline) // We've got the whole line
{
dosomething(longline);
free(longline);
longline = NULL;
uselongline = 0;
} else {
uselongline = 1;
}
}
else
{
dosoemthing(str);
}
}
Note that 8192 may not be sufficient for some purposes. We had an example of badly written software that read a symbol file. When using templates in C++, you can get pretty long symbols. The software was happy with symbols up to about 1500 characters, anything longer would crash(!), but our symbol file had some 9000 character long strings.
The important point here is that we (sometimes) need to recognize that we get input beyond what we have space for, and we need to do SOMETHING about it. What is right in one case may be wrong in another.
--
Mats