Thanks for the help, I will attempt to swap gets() for fgets(). I have done some reading and understand that fgets() is a safer method, but I haven't gotten it to work yet. When I replace gets() with fgets(), my execv() call does not work.
I am attempting to alter the contents of an array of characters in order to alter the PATH of my shell program. I assign the contents of my temporary newPath at index i to the original path, and then I print the contents of path at i to make sure the array elements have changed. However, when I call getPATH the array that is printed is my original character array "/bin/". How do I alter the contents and ensure they stay that way?
char path[50] = "/bin/"; if (strcmp(str, "getPATH") == 0){ //getPATH function printf("%s\n", path); } else if (strcmp(str, "setPATH") == 0){ //setPATH function printf("Set PATH > "); char newPath[50]; gets(newPath); printf("%s\n", newPath); for (int i = 0; i < strlen(newPath); i++){ path[i] = newPath[i]; printf("%c\n", path[i]); } } Output:
> getPATH /bin/ > setPATH Set PATH > newpath newpath n e w p a t h > getPATH /bin/ > Full code:
#include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <string.h> #include <stdlib.h> int main(void){ while (1){ pid_t pid; char path[50] = "/bin/"; char str[50]; printf("> "); //fgets(str, 50, stdin); //Could never get fgets to work, dunno why gets(str); //I know gets is worse but fgets won't work //printf("%s\n", str); //why does c work like this if (strcmp(str, "exit") == 0){ //exit condition return 0; } else if ((pid = fork()) == 0){ //child process char hist[20][50]; if (strcmp(str, "getPATH") == 0){ //getPATH function printf("%s\n", path); } else if (strcmp(str, "setPATH") == 0){ //setPATH function printf("Set PATH > "); char newPath[50]; gets(newPath); printf("%s\n", newPath); strcpy(path, newPath); printf("%s\n", path); //for (int i = 0; i < strlen(newPath); i++){ //path[i] = newPath[i]; //printf("%c\n", path[i]); //} } else if (strcmp(str, "history") == 0){ } else { char *token = strtok(str, " "); //tokenize input command char *toks[20]; toks[0] = token; int numarg = 1; while (token != NULL){ token = strtok(NULL, " "); toks[numarg] = token; numarg++; } strcat(path, toks[0]); //concatenate command to path //int rv = execvp(toks[0], toks); int rv = execv(path, toks); if (rv == -1){ printf("Command Error\n"); } } } else{ wait(NULL); } } return 0; } https://stackoverflow.com/questions/66593488/altering-the-contents-of-an-array March 12, 2021 at 10:48AM
没有评论:
发表评论