I'm another CS beginner working on a simple Shell. At the moment I am trying to change the current directory if an argument is passed, else, report to the current directory.
I tried using chdir()
in my program, but it's apparently not working. I tried passing a char*
arguments which is tokenized. I also tried with argv[1]
, but I must be doing something wrong because neither seems to work.
Also, I'm not exactly sure how to make the argument pointer (containing the directory string) static, so that when i use putenv(ARGUMENT HERE) there are no issues.
Here is the pertaining part of my code:
else if (strncmp(command[0], "cd", 2) == 0)
{
char *argmnts = strtok(0, " ");
if (arguments != NULL)
{
chdir(argmnts);
putenv(argmnts); // THE ARG STRING NEEDS TO BE A STATIC COPY
getcwd(promptBuff, sizeof(argmnts));
}
}
The pointer argmnts points to the tokenized argument part from: char strnBuffer[1000]
which has already been tokenized for the command: command[0] = strtok(strnBuffer, " ");
I really appreciate any help/insight.
Thank you.
You probably have a '\n'
left over on the end of the input line. Your strtok
only recognizes space as separator, so it won't touch the newline. chdir("dir\n")
will fail unless you actually have a directory with the newline at the end of its name.