stdin を介してユーザーからファイル名を取得し、open() でファイルを開き、それをファイル記述子に割り当ててから、そのファイルの内容を stdout に出力したいと考えています。これは私のコードで、正しく動作していません。
問題:
- printf("ファイル名を入力"); ステートメントは決して表示されません
- ファイルを開くことはありません。代わりに、ユーザーが入力したものはすべて画面に出力され、「そのようなファイルまたはディレクトリはありません」というエラーメッセージが出力され、プログラムが終了します
- プログラムが存在した後、ターミナルのプロンプトの前に「ファイル名を入力してください」と表示されます
コード:
{
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);
}
}
}
コンソール:
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...?