Basic Cli Program in C

Okay so overall im trying to complete a basic CLI C program which will complete functions such as clear, quit, cd, ls, help (bring up the unix man) etc.. i altered my code and so far i have this, im getting segmination error when trying to execute the cd command part of the program, (im very new to c btw);

    #include<stdio.h>
    #include<stdlib.h>
    #include<string.h>
    #include<unistd.h>

    int main (int argc, char *argv[])
    {
      char input[] = " ";
      char *argument;
     while(strcmp(input, "quit")!= 0)
      {


      printf("$");
      scanf ("%s", input);

     if(strcmp(input,"clear") == 0)
     {
       printf("\e[1;1H\e[2J");
      }

    else if(strcmp(argv[1],"cd") == 0)
     {


      if(chdir(argv[2]) == -1)
      {
         printf("\n directory does not exists");
       }

     }



    else if(strcmp(input, "echo") == 0)
     {
    char str[50];
    scanf("%[^\n]+", str);

    printf(" %s", str);
     }





  }

 }
5

2 Answers

input is declared as a ' ' (space) character. It will never match 'cd'.

This is probably more along the lines of what you want to achieve, where the first parameter is the command (cd), and the second will be the directory:

int main (int argc, char *argv[])
  {

    char *argument;

  if(strcmp(argv[1],"cd") == 0)
 {


    if(chdir(argv[2]) == -1)
    {
       printf("\n directory does not exists");
    }

  }

Edit Also please note that there is no need for the else satement. If chdir does not return an error, it will change the directory, thus no need to call it again in an else.

Additionally, another tip for using system calls in general, it would be of great help if you print the error number returned by the system upon a failure in system call. This will make things easier when things start going wrong. To do this simply include <errno.h>' and modify the printf to printerrno` which gives specific details about the error:

printf("Chdir error: %d", errno);

For instance chdir() does not only return an error when the directory does not exist, but also for example if you do not have permissions to view the contents of the directory. See the man page for a list of possible errors.

1

To implement your own shell, you need to take input directly from stdin, not from command-line arguments (argv) from another shell. The basic pattern is like this:

  1. Read input
  2. Execute command
  3. Print results
  4. Loop back to step 1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sophia Al-Mansoor

Sophia Al-Mansoor

Global Business & E-Commerce Reporter

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.

Share this article
Twitter Facebook Pinterest