I want to get a file name from a user via stdin, open the file with open() and assign it to a file descriptor, then print the contents of that file to stdout. This is my code, and it's not working properly.
Problems:
- the printf("enter filename"); statement is never showing up
- it never opens the file; instead whatever the user inputs is printed to the screen and then the "no such file or directory" error message is printed and the program exits
- after the program exists i see "enter filename" printed before the prompt in terminal
CODE:
{
printf("Enter the filename: ");
read(STDIN_FILENO, userInput, sizeof(userInput));
if((input_file1 = open(userInput, O_RDONLY)) < 0)
{
perror(userInput);
exit(1);
}
while((n = read(input_file1, buffer, sizeof(buffer))) > 0)
{
if((write(STDOUT_FILENO, buffer, n)) < 0)
{
perror("failed to write to standard-out");
close(input_file1);
exit(1);
}
}
}
Console:
machine{user1}168: ls // to show that the file exists
a.out backup file1
machine{user1}170: ./a.out
file1 // this is user input
file1 // this is printed for no reason
: No such file or directory // ????
Enter the filename: machine{user1}171: // now the prompt is printed...?