6
int main(int argc, char **argv)
{
  char input[150];
  char change[2] = "cd";
  char *directory;

  while(1) {
      prompt();
      fgets(input, 150, stdin);

      if(strncmp(change, input, 2) == 0) {
          directory = strtok(input, " ");
          directory = strtok(NULL, " ");

          printf(directory);
          chdir(directory);
          perror(directory);

      }

      if(feof(stdin) != 0 || input == NULL) {
          printf("Auf Bald!\n");
          exit(3);
      }
  }
}

when i start this and type in "cd test" i get "no such file or directory". But there is the directory "test".

Runs on Arch Linux.

whoan
  • 8,143
  • 4
  • 39
  • 48
csczigiol
  • 73
  • 1
  • 5
  • Check your `directory` string like this: `printf("directory = [%s]\n", directory);` in case you have a stray linefeed or other unwanted/invisible characters in the name. – Paul R Nov 27 '12 at 19:02
  • `char change[2] = "cd"` is assigning an array of size 3 to a variable that is of size 2. Use `char change[] = "cd"` instead. – William Pursell Nov 27 '12 at 19:04
  • @WilliamPursell- Actually, he is using `strncmp(...2)`, so it is legal, although yours is a good practice anyway. – rodrigo Nov 27 '12 at 19:11
  • possible duplicate of [Changing Working Directories in linux shell in a C Program](http://stackoverflow.com/questions/6920483/changing-working-directories-in-linux-shell-in-a-c-program) – Jonathan Leffler Apr 07 '15 at 04:34

1 Answers1

4

From the man page:

fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer.

The problem is there's a newline character '\n' at the end of your string that you got from fgets(), you need to remove it:

fgets(input, 150, stdin);
input[strlen(input)-1] = '\0';

Also:

char change[2] = "cd";

That should be change[3], it's 2 (for "cd") + 1 for the NULL terminator '\0' which is automatically placed for you.

Then it should work.

EDIT:

A different alternative is to change the strtok() call such that:

directory = strtok(NULL, " \n");

This will work if the user enters the string via the enter key or via the EOF (ctrl + d on Linux) character... I'm not sure how likely the second is for a user to do... but it couldn't hurt!

Mike
  • 47,263
  • 29
  • 113
  • 177
  • 2
    Shouldn't be better to write `strtok(..., " \n")`, just in case the string ends with an EOF, or something? – rodrigo Nov 27 '12 at 19:13
  • @rodrigo - Yes, that would be better if there was an EOF. I guess I was assuming the user would type "cd " rather than "cd "... but you never know! Edited the answer to cover that. – Mike Nov 27 '12 at 19:24
  • And why to limit to `" \n"` and not `" \t\n\r"`, just for fun? – rodrigo Nov 27 '12 at 19:53