<stdio.h>
input/output routines are buffered (see stdio(3) & setbuf(3). You need to call fflush(3) (on recent libc, it is implicitly called for stdout
if you read with fgets
or scanf
). And you really should avoid mixing file descriptors and FILE
handles on the same output or input (see fileno(3) but always call fflush
....).
So replace
printf("Enter the filename: ");
read(STDIN_FILENO, userInput, sizeof(userInput));
with
printf("Enter the filename: \n");
fflush(NULL);
if (!fgets(userInput,sizeof(userInput),stdin))
{ perror("fgets"); exit(EXIT_FAILURE); };
Actually here the fflush
could be avoided if you keep the very important terminating \n
(newline). If you don't want any newline you should better call fflush
(but some libc are calling it for you).
Calling fflush
too much or too often is much less harmful (because on all already flushed stream it is a no-op) than calling it too little or not enough.
But you should learn about getline(3) (to avoid fixed-length lines). On Linux and GNU systems readline is worth using: it enables you to give a sexy prompt, and your user to edit the typed line.