简体   繁体   English

调用fgets将结果打印到标准输出

[英]Call to fgets results in string printing to stdout

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

When I run the function and type in a string, I see the string printed back in stdout. 当我运行该函数并键入一个字符串时,我看到该字符串在stdout中打印回。 I am sure I have an issue with a buffer, but I can't seem to figure this out. 我确定缓冲区有问题,但似乎无法解决。

When you run it if you see: 运行时,如果您看到:

./program
input<CR>
input
<prompt>

Then the code you provided was not responsible for doing that. 然后,您提供的代码不负责。 Use some debug statements or a debugger to figure out where that echo is coming from, because that isn't what fgets does. 使用一些调试语句或调试器来找出回声的来源,因为那不是fgets所做的。

If you are seeing: 如果您看到:

./program
input<CR>
<prompt>

Then that is just how terminals work. 这就是终端的工作方式。 They will echo back the text as you type unless you disable that feature (useful for entering passwords). 除非您禁用该功能(用于输入密码),否则它们将在您键入内容时回显文本。

When you type characters into the console, they are echoed back to you. 当您在控制台中键入字符时,它们会被回显给您。 The characters will still be read when you read from stdin . stdin读取时,仍将读取字符。

Alternatively you can pipe the output of a program into your own, or redirect a file to stdin. 或者,您可以将程序的输出通过管道传输到自己的程序中,或将文件重定向到stdin。 In those two cases, the characters will not be echoed: 在这两种情况下,将不会回显字符:

echo Program output | ./myprog

or: 要么:

./myprog < fileinput.txt

edit - Sounds like it's a terminal problem. 编辑 -听起来像是终端问题。

You haven't stated what system you are using or how you are interfacing with it, but I can get this behaviour by connecting to a system via SSH with PuTTY. 您尚未说明正在使用什么系统或如何与之交互,但是我可以通过使用PuTTY通过SSH连接到系统来获得此行为。

I change the terminal settings to force on both "Local echo" and "Local line editing". 我更改了终端设置,以同时启用“本地回显”和“本地行编辑”。 Then I get the line echoed whenever I press enter. 然后,每当我按Enter键时,行就会回显。 Obviously only one of those should be on. 显然,只有其中之一可以使用。 Preferably "Local echo". 最好是“本地回声”。

A common cause of this is having echoing enabled in both your terminal (presumably an emulator these days) and in the OS terminal driver. 造成这种情况的一个常见原因是在终端(目前可能是仿真器)和OS终端驱动程序中都启用了回显。 Assuming you're using Unix, does the problem go away if you do: 假设您使用的是Unix,如果您这样做,问题是否会消失:

stty -echo

before running your program? 在运行程序之前?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM