Note that there are some explanatory texts on larger screens.

plurals
  1. POCharacter arrays, and pointers how to use strtok and strcmp
    text
    copied!<p>I'm writing a linux shell for my operating systems class. I've knocked out the majority of it but I'm stuck on simple string comparisons. I've everything I can think of. strcmp should take in \0 terminated strings and return 0 for equal but that doesn't seem to be working and even stepping through the array and checking each char isn't working either. I currently have cmd[0] in the strcmp I know thats not right it needs to be null terminated but I've tried using strcpy and strcat \0 to another string. If someone could point out my mistake it would be much appreciated.</p> <pre><code>//Matthew Spiers //CSC306 #include &lt;string.h&gt; #include &lt;sys/types.h&gt; #include &lt;sys/wait.h&gt; #include &lt;iostream&gt; #include &lt;unistd.h&gt; #include &lt;stdlib.h&gt; using namespace std; void ckCmd(char dir[]); int main(){ pid_t pid; char cdstr[4] = "cd"; char str[50]; char *cmd[3]; char *pstr; char temp[50]; char dir[50] = "/bin/"; while(1){ pid = fork(); if(pid &lt; 0){ fprintf(stdout, "Fork Failed"); } else if(pid == 0){ fprintf(stdout, "\e[36m306.SH&gt;\e[0m"); fgets(str, 50, stdin); for(int i =0; i&lt;50; i++){ if(str[i] == '\n'){ str[i] = '\0'; } } strcpy(temp, str); // Make a copy of original string cmd[0] = strtok(str, " "); for(int i =1; i&lt;3; i++){ cmd[i] = strtok(NULL, " "); } strcat(dir, cmd[0]); cout &lt;&lt; cmd[0]; pstr = strtok(temp, " "); //pull out only first token //Change Directory if(!strcmp(pstr, "cd")){ //if first token is cd //either branch to a routine just change directory //ie branch and change directory } //ckCmd(temp); execlp(dir, cmd[0], cmd[1], cmd[2], NULL); _exit(0); } else{ wait(NULL); } } } void ckCmd(char str[]){ char *p; p = strtok(str, " "); if(p[0] == 'c'){ chdir("new"); } } enter code here </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload