Reputation: 4847
I am a complete beginner in C programming, so please have some patience with me. I am trying to input a file name from the user in the console and I want to print a helpful message that prompts the user to enter the filename he wants to open. But when I run this in the command prompt, the cursor waits for the input first and after I enter some text and hit Return, I see the helpful prompt that I wanted to print before the input. Here is the code snippet.
char filename[40];
fputs("enter the file name: ", stdout);
fflush(stdout);
fgets(filename, sizeof(filename), stdin);
I can't see where I am going wrong with this. I would really appreciate if some one could explain why this happens.
Upvotes: 1
Views: 7517
Reputation: 2180
This works for me with 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);
On a *nix machine, in assembly, to read and write:
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
This is some Windows assembly I got from a teacher:
.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
Upvotes: 0
Reputation: 2961
I do not see any issues with the code you have pasted, works fine with gcc. It must be something to do with the stdout not being flushed, which could be specific to the compiler you are using...
Upvotes: 1