Search code examples
cfgetscdchdir

How to use chdir system function


I am trying to use chdir to change the working directory of my process. Say I have an apple directory in my current directory. Why is it that when I input apple in the prompt the returned result is -1? Is it because when I enter apple, the '\n' character is also put at the end of the string? Besides, what is the meaning of changing directory if I could just use a variable to store it?

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

int main(void){
    char path[256];
    fgets(path, 256, stdin);
    printf("%s", path);
    int result = chdir(path);
    if(result != 0){
        printf("%d\n", result);
    }
}

Solution

  • fgets() suffixes the result with might (if no EOF had been received) read a new-line (\n on IXish systems) and passing this to chdir() makes the latter choke as the directory name to change to most likley does not carry a trailing new-line.

    From man fgets() (Italics by me):

    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.


    A note on debugging: If you'd put the "string" to print (as read by fgets()) in quotes like this

    printf("'%s'", path);
    

    you might have noticed the trailing \n.