我想通过标准输入从用户那里获取文件名,使用 open() 打开文件并将其分配给文件描述符,然后将该文件的内容打印到标准输出。这是我的代码,它不能正常工作。
问题:
- printf("输入文件名");声明永远不会出现
- 它永远不会打开文件;相反,无论用户输入什么,都会打印到屏幕上,然后打印“没有这样的文件或目录”错误消息,然后程序退出
- 程序存在后,我看到在终端提示之前打印了“输入文件名”
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...?
<stdio.h>
输入/输出例程是buffered (see stdio(3) & 设置缓冲区(3)。你需要打电话冲洗(3)(在最近的 libc 上,隐含地要求stdout
如果你阅读fgets
or scanf
)。你真的应该避免混合文件描述符和FILE
处理相同的输出或输入(参见文件号(3)但总是打电话fflush
....)。
所以更换
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); };
其实这里的fflush
如果您保留非常重要的终止,则可以避免\n
(新队)。如果你不想要任何换行符,你最好打电话fflush
(但有些 libc 正在为你调用它)。
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.
但你应该了解获取线路(3)(以避免固定长度的行)。在 Linux 和 GNU 系统上readline值得使用:它使您能够给出性感的提示,并且您的用户可以编辑键入的行。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)