【问题标题】:I can not access to if statement in c我无法访问 c 中的 if 语句
【发布时间】:2021-05-04 20:21:35
【问题描述】:

我试图访问 appendinoutif 语句,但目前只有“附加”有效。

我不知道为什么它不适用于 inout。你能告诉我是什么问题吗?

如果我输入“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 会在程序运行之前消耗&gt;
  • @헬창공돌이:您没有展示如何设置变量args,但无论如何,如果您真的将其调用为ls &gt; hi.txt,,则只有ls 可用。程序的第一个参数是程序名本身,第二个参数是ls。就是这样。

标签: c shell unix append system


【解决方案1】:

您的for 循环中有(潜在的)未定义行为:第二个和第三个if 语句应该是else if,而不是(毕竟,实际上只能满足三种可能性中的一种)。

就目前而言,当 first if 块 (if(strcmp(args[i],"&lt;")==0)) 执行时,该块内的代码将 argv[i] 设置为 NULL 指针,然后将其用作second if 测试中strcmp 的第一个参数。对strcmp 的调用会导致未定义的行为,因为NULL 不是指向nul 终止字符串的指针。

当进入 second if 块时会发生类似情况:third 中的测试将导致未定义的行为。

来自cppreference

如果 lhs 或 rhs 不是指向的指针,则行为未定义 以 null 结尾的字节字符串。


所以,当你的操作符是&gt;&gt;(“append”)时,未定义的行为不会被调用,因为前两个if块都没有被执行;但是,对于&lt;&gt;,输入其中一个argv[i] 设置为NULL,并且出现UB; UB 可能包含 strcmp 函数“错误地”返回零,因此将执行其他 if 块中的一个或两个,从而导致您的程序给出不正确的结果。

【讨论】:

  • 非常感谢!
猜你喜欢
  • 2017-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-09
  • 1970-01-01
  • 2019-04-06
  • 1970-01-01
相关资源
最近更新 更多