首页 > 解决方案 > 意外的 getc(stdin) 在 EOF 之前等待读取文件的最后一个字符

问题描述

我的应用程序是用 Eclipse CDT Neon (4.6.2RC3) 和 gcc (Debian 6.3.0-18) 6.3.0 20170516 构建的

#include <stdio.h>
#include <stdlib.h>

int
main()
{
    for (int i = 0;;i++) {  /* Loop through characters. */
        int ch;
        ch = getc(stdin);   /* Read the next character. */
        if (i < 100 || i > 67730) fprintf(stderr, "%i(%i) ", i, ch);
        else if (i == 100) fprintf(stderr, " ----- ");
        if (ch == EOF)
            break;      /* Exit loop on end-of-file. */ 
    }
    fprintf(stderr, "\n\n*** finished successfully ***\n");
    return 0;
}

这是我的编译选项:-O0 -pedantic -Wall -Wextra -c -ggdb -fmessage-length=0 -Wno-implicit-function-declaration. 我借助管道传输到stdin.

当我从控制台运行它时,一切都很好。这是从控制台运行时正常输出的结尾:

./myprogram < inputfile.pdf

67825(32) 67826(54) 67827(10) 67828(10) 67829(12) 67830(-1) 

*** finished successfully ***

但是当我从 Eclipse CDT 以调试模式运行它时,它会无限期地等待 EOF(第 67830 个)之前的最后一个字符(第 67829 个),并且程序永远不会退出。如果我暂停执行,我可以检查它是否卡在行内ch = getc(stdin);。这是此时的堆栈:

Thread #1 [ArithmeticCoder] 29598 [core: 5] (Running : User Request)    

Thread #1 [myprogram] 29598 [core: 6] (Suspended : Signal : SIGINT:Interrupt)   
    __read_nocancel() at /build/glibc-p3Km7c/glibc-2.24/io/../sysdeps/unix/syscall-template.S:84 0x7ffff7811700 
    _IO_new_file_underflow() at /build/glibc-p3Km7c/glibc-2.24/libio/fileops.c:600 0x7ffff77a9a00   
    __GI__IO_default_uflow() at /build/glibc-p3Km7c/glibc-2.24/libio/genops.c:413 0x7ffff77aab02    
    _IO_getc() at /build/glibc-p3Km7c/glibc-2.24/libio/getc.c:38 0x7ffff77a54f0 
    main() at /.../WorkSpace/myprogram/src/myprogram.c:20 0x555555554f08    

我努力了:

我的设置可能会出现什么样的错误?

请问有什么想法吗?

标签: cioeclipse-cdt

解决方案


推荐阅读