Having an issue with chdir. Tried to minimize the code as much as I could here. What I'm trying to do:
- get input from user
- chdir to the directory referenced by the user's input
It's giving me a -1 all the time. I'm sure I'm doing something wrong, perhaps you can help me figure it out?
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <errno.h>
#include <stdio.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <netdb.h>
#include <time.h>
int strinit(char *s1, int len);
int main(int nArg, char* pszArgs[])
{
char userinput[256];
strinit(userinput,sizeof(u
serinput))
;
int i,j,k;
printf("Directory: ");
fgets(userinput,sizeof(use
rinput),st
din);
printf("Attempting to chdir to %s\n",userinput);
i=0;
i=chdir(userinput);
printf("Returned: %d\n",i);
return 0;
}
int strinit(char *s1, int len)
{
int i;
for (i=0; i<len; i++) {
s1[i]=0;
}
return 0;
}
Here's what I get on the output:
jchristns-macbook:C jchristn$ mkdir test
jchristns-macbook:C jchristn$ ls -la test
total 0
drwxr-xr-x 2 jchristn staff 68 Mar 15 17:06 .
drwxrwxrwx 180 jchristn staff 6120 Mar 15 17:06 ..
jchristns-macbook:C jchristn$ ./chdir
Directory: test
Attempting to chdir to test
Returned: -1
jchristns-macbook:C jchristn$ ./chdir
Directory: test/
Attempting to chdir to test/
Returned: -1
jchristns-macbook:C jchristn$ ./chdir
Directory: /Users/jchristn/Desktop/Do
cuments/C/
test
Attempting to chdir to /Users/jchristn/Desktop/Do
cuments/C/
test
Returned: -1
jchristns-macbook:C jchristn$ ./chdir
Directory: /Users/jchristn/Desktop/Do
cuments/C/
test/
Attempting to chdir to /Users/jchristn/Desktop/Do
cuments/C/
test/
Returned: -1
jchristns-macbook:C jchristn$
Start Free Trial