1

我是 C 编程的初学者,所以请耐心等待。我正在尝试在控制台中输入用户的文件名,并且我想打印一条有用的消息,提示用户输入他想要打开的文件名。但是当我在命令提示符下运行它时,光标首先等待输入,在我输入一些文本并按回车后,我看到了我想在输入之前打印的有用提示。这是代码片段。

 char filename[40];
 fputs("enter the file name: ", stdout);
 fflush(stdout); 
 fgets(filename, sizeof(filename), stdin);

我看不出我哪里出了问题。如果有人能解释为什么会发生这种情况,我将不胜感激。

4

2 回答 2

1

我没有看到您粘贴的代码有任何问题,可以正常使用 gcc。它必须与未刷新标准输出有关,这可能特定于您正在使用的编译器......

于 2012-08-21T20:06:10.847 回答
0

这对我有用gcc version 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.11.00)

char path[100];

printf("Give a path: ");

// Max length of 99 characters; puts a null terminated string in path, thus 99 chars + null is the max
scanf("%99s", path);

printf("This is your path: %s\n", path);

在 *nix 机器上,在汇编中,读取和写入:

read:   mov $0x03, %rax # Syscall Read
        mov $0x00, %rbx # Stdin
        mov $Buff, %rcx # Address to read to
        mov $BuffLen, %rdx  # Bytes to read
        int $0x80           # Call

write:  mov $0x04, %rax # Syscall Write
        mov $0x01, %rbx # Stdout
        mov $Buff, %rcx # Address to write from
        mov $BuffLen, %rdx  # Bytes to write
        int $0x80           # Call

这是我从老师那里得到的一些 Windows 程序集:

.386
.MODEL FLAT

ExitProcess PROTO NEAR32 stdcall, dwExitCode:DWORD

GetStdHandle PROTO NEAR32 stdcall, nStdHandle:DWORD

ReadFile PROTO NEAR32 stdcall, hFile:DWORD, lpBuffer:NEAR32, NumberOfCharsToRead:DWORD,
     lpNumberOfBytesRead:NEAR32, lpOverlapped:NEAR32

WriteFile PROTO NEAR32 stdcall, hFile:DWORD, lpBuffer:NEAR32, NumberOfCharsToWrite:DWORD,
     lpNumberOfBytesWritten:NEAR32, lpOverlapped:NEAR32

STD_INPUT  EQU -10
STD_OUTPUT EQU -11

cr  EQU 0dh
Lf  EQU 0ah

.STACK
.DATA

InMsg   BYTE    14 dup (?)
msgLng  DWORD   $ - InMsg ;
read    DWORD   ?
written DWORD   ?
hStdIn  DWORD   ?
hStdOut DWORD   ?

.CODE
_start:
        INVOKE GetStdHandle, STD_INPUT
        mov     hStdIn, eax
        INVOKE ReadFile, hStdIn, NEAR32 PTR InMsg, msgLng, NEAR32 PTR read, 0
    INVOKE GetStdHandle, STD_OUTPUT
    mov hStdOut, eax
        INVOKE WriteFile, hStdOut, NEAR32 PTR InMsg, msgLng, NEAR32 PTR written, 0
    INVOKE ExitProcess, 0

PUBLIC  _start
END
于 2012-08-21T20:27:36.643 回答