简体   繁体   中英

Execv function in C not reading a variable that is passed in as an argument

So I am building my own shell and one of the commands I want is the "cat" function. To do this, I am using the execv function and passing in the correct bin path of "cat" as well as the file name that I want to concatenate and print to the terminal.

The code below works perfectly fine, but I am hard coding in the file name that I want to "cat"

void cat(char *fileName)
{
    char *bin_path = "/bin/cat";
    printf("%d\n", strncmp(fileName, "junk.txt", strlen("junk.txt"))); // returns 0, meaning equal values
    char *args[] = {bin_path, "junk.txt", NULL};
    execv(bin_path, args);
}

The output from above is shown below argument is hardcoded in

But I want to be able to make this function dynamic and have the file name be passed into the function, so that's why I have the variable fileName as a parameter. You can see that I am comparing the string literal "junk.txt" with fileName variable and it returns 0, meaning they are EQUAL! But when I pass in the variable fileName to the execv function, it doesn't work. Please see my broken code below

void cat(char *fileName)
{
    char *bin_path = "/bin/cat";
    printf("%d\n", strncmp(fileName, "junk.txt", strlen("junk.txt"))); // returns 0, meaning equal values
    char *args[] = {bin_path, fileName, NULL};
    execv(bin_path, args);
}

no file or directory that matches that name

Anyone have any idea why that is?

Likely you read the file name as a whole line and got the new-line character at the end of the line. strncmp only compares up to the number of characters you tell it, so the zero result does not prove the strings are equal. We can even see the new-line in the error message from cat : After “junk.txt”, its “:” is on a new line.

Change the calling routine to remove the unwanted new-line character from the name.

In the future, always provide a Minimal Reproducible Example with debugging questions. The error in this case was in code you did not show, in the calling routine, and that is why a MRE should always be provided.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM