【发布时间】:2021-05-04 20:21:35
【问题描述】:
我试图访问 append、in 和 out 的 if 语句,但目前只有“附加”有效。
我不知道为什么它不适用于 in 和 out。你能告诉我是什么问题吗?
如果我输入“ls > hi.txt”,args 的内容是:
args[0] = ls
args[1] = >
args[2] = hi.txt
args[3] ='\0'
for(i = 0; args[i] != (char*)'\0';i++)
{
if(strcmp(args[i],"<")==0)
{
args[i] = NULL;
printf("IAMHERE\n");
strcpy(input,args[i+1]);
in = 2;
}
if(strcmp(args[i],">")==0)
{
args[i] = NULL;
printf("IAMHERE\n");
strcpy(output,args[i+1]);
out = 2;
}
if(strcmp(args[i],">>")==0)
{
args[i] = NULL;
strcpy(output,args[i+1]);
append = 2;
}
}
if(append)
{
printf("yohere\n");
if((fap = open(output,O_RDWR|O_APPEND))<0)
{
perror("Could not open outputfile");
exit(0);
}
dup2(fap,STDOUT_FILENO);
close(fap);
}
if(in)
{
printf("yohere\n");
if((fin = open(input,O_RDONLY,0))<0){
perror("Couldn't open input file");
exit(0);
}
dup2(fin,0);
close(fin);
}
if(out)
{
printf("yohere\n");
if((fout = creat(output,0644))<0){
perror("Could not open the outputfile");
exit(0);
}
dup2(fout,STDOUT_FILENO);
close(fout);
}
【问题讨论】:
-
你能显示什么是
args及其内容并编辑here plz -
请注意,如果在命令行上键入,bash 会在程序运行之前消耗
> -
@헬창공돌이:您没有展示如何设置变量
args,但无论如何,如果您真的将其调用为ls > hi.txt,,则只有ls可用。程序的第一个参数是程序名本身,第二个参数是ls。就是这样。
标签: c shell unix append system