调用fgets导致字符串打印到stdout

时间:2012-11-20 20:43:11

标签: c fgets

void deleteFile( FAT *allotable ) {
/* PRECONDITION: This function expects a FAT structure that is valid.
 * POSTCONDITION: A file is flagged as removed from the disk and it will 
 * be possible to write over it
 */

    // Local variables
    unsigned char test[9] = { 0 };

    // Select file to remove
    // TODO: The user will select the file to remove based on the 
    // listing in listDir
    // For testing, we are removing file at location 0 in the entry
    fgets( test, NAME_SIZE, stdin );
    return;
}

当我运行该函数并输入一个字符串时,我看到字符串打印在stdout中。我确信我的缓冲区存在问题,但我似乎无法解决这个问题。

3 个答案:

答案 0 :(得分:1)

当你运行它时,如果你看到:

./program
input<CR>
input
<prompt>

然后您提供的代码不负责这样做。使用一些调试语句或调试器来确定回声的来源,因为这不是fgets所做的。

如果你看到:

./program
input<CR>
<prompt>

那就是终端的运作方式。除非您禁用该功能(对输入密码很有用),否则他们会在您键入时回显文本。

答案 1 :(得分:0)

当您在控制台中键入字符时,它们会回显给您。从stdin读取时,仍会读取字符。

或者,您可以将程序的输出通过管道传输到您自己的程序中,或者将文件重定向到stdin。在这两种情况下,字符将不会被回显:

echo Program output | ./myprog

或:

./myprog < fileinput.txt

编辑 - 听起来像是一个终端问题。

您尚未说明您正在使用的系统或与之接口的方式,但我可以通过SSH与PuTTY连接到系统来获得此行为。

我将终端设置更改为强制“本地回显”和“本地行编辑”。然后每当我按回车键时,我都会回显该线。显然只有其中一个应该开启。最好是“本地回声”。

答案 2 :(得分:0)

这种情况的一个常见原因是在您的终端(可能是最近的仿真器)和OS终端驱动程序中启用了回显功能。假设您正在使用Unix,如果您这样做,问题就会消失:

stty -echo

在运行程序之前?