Phil said:
I'm glad someone spotted that and had a double-take.
I leave it as a just-for-fun challenge to c.l.c to provide an
example (which doesn't have other issues) by mid-weekend (when
I'll spill the beans). 1 kudo to anyone who gets my answer, 2
kudos to anyone who gets a fundamentally different answer.
I'll take that on. Let us assume the unlimited input data has been
captured in 'badfile.txt'. We need a means of reading that file
using gets, and where no buffer overrun can ever occur. I am going
to apply my ggets in the preliminary, but not in the final read.
This is valid since ggets is written in purely standard C. You can
get ggets at:
<
http://cbfalconer.home.att.net/download/ggets.zip>
I will omit the necessary file openings and closings. Provisions
need to be taken to avoid altering badfile.txt between the first
open and the final close (after reading with gets).
First, we access and open badfile.txt, forming a rewound FILE* in
badf.
char *buf, *lbuf;
size_t blgh, lblgh;
if (0 != fggets(&buf, badf))
abort("No legible data in badfile.txt");
lblgh = strlen(buf);
lbuf = buf;
while (0 == fggets(&buf, badf)) {
blgh = strlen(buf);
if (lblgh < blgh) {
free(lbuf); lbuf = buf;
}
else free(buf);
}
/* Now, barring i/o errors, lbuf contains the longest line */
/* rewind badf, i.e. the file badfile.txt. */
while (gets(lbuf)) {
/* do whatever you wish with lbuf, but don't free it. */
}
/* and you have read that file cleanly with gets */
This needs revisions to ensure that the input file is always
stdin. When that is done we can also replace fggets with ggets
(which is just a macro).