gpt4 book ai didi

c - 输入重定向 - 如果打开文件进行写入失败

转载 作者:行者123 更新时间:2023-11-30 17:34:58 25 4
gpt4 key购买 nike

我在linux(c语言)中实现了一个简单的shell。我在终端中检查了这一行: ./myprogram < a.txt当我没有 a.txt 的任何权限时。这样的myprogram用空文件运行。问题:如何在 open() 之后发送空文件失败了?

示例代码:

if( fork() == 0 ){
int f_in = open("a.txt", O_RDONLY);
if(f_in == -1){
perror("open input");
f_in = ???
}
dup2(f_in, STDIN_FILENO);
execvp(args[0], args);
}

新程序的标准输入应该为空,只有 EOF。

最佳答案

在这里,您可以以读/写模式打开文件,如果文件可用,那么您将从打开文件中获得 f_in 并包含文件中可用的数据,如果文件不可用,则将创建仅具有 EOF 的文件,您将给出该文件f_in 继续进行。愿它对你有帮助。示例:

if( fork() == 0 ){
int f_in = open("a.txt", O_RDWR);
if(f_in == -1){
perror("open input");
}
dup2(f_in, STDIN_FILENO);
execvp(args[0], args);
}

关于c - 输入重定向 - 如果打开文件进行写入失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23137938/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com