C printf/read 冲突

标签 c parsing io

我目前正在尝试让这段代码正常工作:

//TODO THIS IS NOT WORKING
printf("WARNING: THE USER INPUT WILL OVERWRITE THE FILE \"%s\". ARE YOU SURE? [Y/N] ", output_file_name);
int c;

while(read(0, &c, 1) == 1) {
    if (((unsigned char) c) == 'y')
        printf("YES");
}

我期望代码做什么: 我期待收到短信

警告:用户输入将覆盖文件“FILENAME”。你确定吗? [是/否]

在命令行中打印。为了能够写一些东西,在按 enter 后,我希望看到文本 YES 打印与前面给定的“y”一样多的次数输入。相反,这就是我得到的:

./myprogram.o
I type things.
Including yyyy
ydkfasjf
yay
Now I'm tired and will press ctrl+d to write EOF to stdin...
WARNING: THE USER INPUT WILL OVERWRITE THE FILE "FILENAME". ARE YOU SURE? [Y/N]YESYESYESYESYESYESYESYES
Matthias@BASH ~/folder/

这里发生了什么?我认为 printf 和 read 函数在某种程度上发生了冲突......有人可以启发我吗?

最佳答案

stdout 通常是 缓冲的。要强制输出在下一行代码之前发生,请将 '\n' 添加到输出或使用 fflush(stdout)

同时将 int c 更改为 char c 以正确将数据读取到 c 中。

printf("WARNING: THE USER INPUT WILL OVERWRITE THE FILE \"%s\". ARE YOU SURE? [Y/N] ", 
    output_file_name);
fflush(stdout); // *****
// int c;
char c;

while(read(0, &c, 1) == 1) {
    if (((unsigned char) c) == 'y') {
      printf("YES");
      fflush(stdout); // *****
    ]
}

关于C printf/read 冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33791865/

相关文章:

java - 在 Java 中从 InputStream 读取时遇到 IOException

c - 构建新编译器的好方法是什么?

将 c 顺序转换为 OpenMP 问题

python - BeautifulSoup (bs4) : How to ignore ending tag in malformed HTML

c - fread() 返回读取字节数 + 1

io - 如何将文本写入本地文件

将字符串与c中的多个数组进行比较

C - 找出所有不同的数字

Python xml - 删除空格以对齐 xml 文档

python-3.x - Python dateutil : AttributeError: module 'dateutil' has no attribute 'parse'