c - 意外的 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
我努力了:
- 与
fgetc
which 非常相似,但结果是相同的。 - 在Eclipse CDT RUN 模式下,它没有到达文件末尾。我假设问题是相同的,并且由于在Eclipse CDT环境下运行此应用程序。
- 换成
ch = getc(stdin); if (ch == EOF)
,int s = fread (&ch, 1, 1, stdin ); if (ch == EOF || s == 0)
结果是一样的!我预计不会,因为他们的行为确实不同。
我的设置可能会出现什么样的错误?
请问有什么想法吗?
解决方案
推荐阅读
- node.js - Node.js | JavaScript堆内存不足,但HEAP只有1GB
- java - 服务器如何将 JWT 令牌返回给客户端?
- sql-server - 消除递归 CTE
- odoo - 在 many2one 小部件中不选择任何内容
- laravel - 更新数据库表中的多行
- c# - 如何设置条形图/条形图的颜色?
- c# - 强制将 DateTimeOffset 转换为 Nullable
- javascript - 使用 render/createElement 将单选按钮链接到 Vue 中的数据
- laravel - Laravel 面包屑有问题
- angularjs - 我可以同时运行一个 AngularJS 组件和一个 Angular 组件吗?