-1
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<string.h>

int main()
{
    char temporaryPath[50];

    fgets(temporaryPath, sizeof(temporaryPath), stdin);

    if(chdir(temporaryPath) == -1)
        printf("Failed to change directory\n"); 

    getcwd(temporaryPath, 1000);
    printf("%s> ", temporaryPath);
}

I have been searching a lot about changing directories but I haven't been able to figure out why chdir() is failing in this case. If I use fgets() instead of hard coding the temporaryPath array, chdir() fails to change directory. Why is that and what could be done to fix it?

Thank you very much :)

Tehmas
  • 83
  • 2
  • 10
  • 6
    `fgets` will include the trailing *newline* (if any) of the input, this is most likely what is causing your error. – Filip Roséen - refp Apr 02 '15 at 18:15
  • @FilipRoséen-refp thank you for replying. It worked like a charm. Though I tested it with a loop and using it in the code will indeed effect performance and using Vlad's method has a disadvantage like you just said. – Tehmas Apr 02 '15 at 18:25
  • Read the line using `fgets`, strip the trailing newline (**if** one is there), continue doing whatever it is that you'd like to do. – Filip Roséen - refp Apr 02 '15 at 18:27
  • Yes but what is the better way to strip the trailing newline? – Tehmas Apr 02 '15 at 18:28

1 Answers1

2
if ( fgets(temporaryPath, sizeof(temporaryPath), stdin) != NULL )
{
   int len = strlen(temporaryPath);
   if ( temporaryPath[len-1] == '\n' )
   {
      temporaryPath[len-1] = '\0';
   }

   // Now that the newline has been trimmed, use temporaryPath. 
}
R Sahu
  • 204,454
  • 14
  • 159
  • 270