C 第一行后达到EOF的标准偏差

C 第一行后达到EOF的标准偏差,c,std,stdin,fgets,eof,C,Std,Stdin,Fgets,Eof,我正在尝试使用type file.txt | myprogram.exe将一个文件传输到我的程序。我用以下文字阅读: 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

我正在尝试使用
type file.txt | myprogram.exe
将一个文件传输到我的程序。我用以下文字阅读:

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;
        }
    }
    ...
}

但是在读取第一行之后,
feof()
返回true,即使文件中有多行。怎么会这样

代码有多个问题:

  • 文件结尾测试不正确:
    feof()
    仅在读取函数失败后提供有意义的信息
  • 重新分配方案被破坏:您测试数组的倒数第二个字节,但是如果行较短,则
    fgets()
    可能没有设置此字节
以下是修复程序的方法:

  • 如果您的系统支持,请使用
    getline()
    getline()
    分配足够大的缓冲区,以便一次读取一整行
  • 或者使用
    fgets
    读取行片段并检查其是否以换行结束

请花点时间阅读,看起来像
,而(第[cbs-2]行)可以读取内部循环中的整个文件,因为它正在检查哪些是未初始化的内存。至于您的算法,它似乎完全错误。如果您想在不知道确切长度的情况下读取一行,请使用
fgets
(就像您正在做的那样),但请检查字符串是否以换行结束。如果结尾没有换行符,那么还有更多的行要读。使用
strchr
strcspn
查找(字符串的)末尾是否有换行符,该换行符可能不是数组的结尾!)。