Search code examples
cshellunixappendsystem

I can not access to if statement in c


I was trying to access the if statements for append, in, and out but only the "append" works for now.

I don't know why it does not work for in and out. Could you please tell me what is the problem?

The args contents, if I type "ls > hi.txt," are:

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

Solution

  • You have (potential) undefined behaviour in your for loop: the second and third if statements should be else if, instead (after all, only one of the three possibilities can actually be satisfied).

    As it stands, when the first if block (if(strcmp(args[i],"<")==0)) is executed, the code inside that block sets argv[i] to a NULL pointer, which is then used as the first argument to the strcmp in the second if test. That call to strcmp causes undefined behaviour, as NULL is not a pointer to a nul-terminated string.

    A similar situation occurs when the second if block is entered: the test in the third will then cause undefined behaviour.

    From cppreference:

    The behavior is undefined if lhs or rhs are not pointers to null-terminated byte strings.


    So, when your operator is >> ("append"), the undefined behaviour is not invoked, because neither of the first two if blocks is executed; however, with < or >, one of those is entered, argv[i] is set to NULL, and the UB occurs; that UB may include the strcmp function 'incorrectly' returning zero, and thus one or both of the other if blocks will be executed, causing your program to give incorrect results.