0

我试图访问 , 的语句,ifappend现在只有“附加”有效。inout

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

args如果我输入“ls > hi.txt”,内容是:

    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);
}
4

1 回答 1

0

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

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

进入第二个 if块时会发生类似的情况:第三个块中的测试将导致未定义的行为。

cppreference

如果 lhs 或 rhs 不是指向空终止字节字符串的指针,则行为未定义。


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

于 2021-01-31T13:24:16.633 回答