I'm trying to pipe a file to my program using type file.txt | myprogram.exe
. I'm reading it in with:
char *line;
struct block *newblock, *cur;
int i, osl, cbs, rs;
int startblock;
/* read in the blocks ... */
while (!feof(stdin) && !ferror(stdin)) {
cbs = 2048;
line = (char *)malloc(cbs + 1);
if (!line) {
perror("malloc");
exit(1);
}
line[cbs] = '\0';
/* read in the line */
if (!fgets(line, cbs, stdin)) {
free(line);
continue;
} else {
while (line[cbs - 2]) {
/* expand the line */
line = (char *)realloc(line, (cbs * 2) + 1);
if (!line) {
perror("realloc");
exit(1);
}
line[cbs * 2] = '\0';
/* read more */
if (!fgets(line + cbs - 1, cbs + 1, stdin))
break;
cbs *= 2;
}
}
...
}
But just after reading the first line, feof()
returns true, even though there are multiple lines in the file. How can that happen?