【发布时间】:2013-11-11 22:05:32
【问题描述】:
我想通过标准输入从用户那里获取文件名,用 open() 打开文件并将其分配给文件描述符,然后将该文件的内容打印到标准输出。这是我的代码,它不能正常工作。
问题:
- 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...?
【问题讨论】:
-
不要混合
FILE*函数(包括printf(),它与fprintf(stdout,...)和same打开文件上的文件描述符函数相同。第一个被缓冲,第二个绕过这种缓冲,随后出现看似奇怪的行为。
标签: c stdin low-level low-level-io low-level-code