问题
I am new in c programming. How can I change directory like /home/jobs/$ans/xxx/
while I have $ans
is a user string I can't chdir
in c program.
My script is below:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char jdir;
printf("Enter job directory:"); /* user input for different directories */
scanf("jdir");
chdir("/home/jobs/%jdir/xxx");
system("ls -ltr");
return(0);
}
How to change directory with chdir
?
回答1:
Use something like:
char jdir[200]
scanf("%s", &jdir);
char blah[200];
snprintf(blah, 199, "/home/jobs/%s/xxx", jdir);
chdir(blah);
回答2:
It seems mildly silly to write this program in C, but if there is a good reason to do so (for instance if it has to be setuid) then you should be a great deal more defensive about it. I would do something like this:
#define _XOPEN_SOURCE 700 /* getline */
#include <stdio.h>
#include <string.h>
#include <unistd.h>
int main(void)
{
char *jobdir = 0;
size_t asize = 0;
ssize_t len;
fputs("Enter job directory: ", stdout);
fflush(stdout);
len = getline(&jobdir, &asize, stdin);
if (len < 0) {
perror("getline");
return 1;
}
jobdir[--len] = '\0'; /* remove trailing \n */
if (len == 0 || !strcmp(jobdir, ".") || !strcmp(jobdir, "..")
|| strchr(jobdir, '/')) {
fputs("job directory name may not be empty, \".\", or \"..\", "
"nor contain a '/'\n", stderr);
return 1;
}
if (chdir("/home/jobs") || chdir(jobdir) || chdir("xxx")) {
perror(jobdir);
return 1;
}
execlp("ls", "ls", "-ltr", (char *)0);
perror("exec");
return 1;
}
The edit history of this answer will demonstrate just how hard it is to get this 100% right - I keep coming back to it and realizing that I forgot yet another case that needs to be defended against.
来源:https://stackoverflow.com/questions/13204650/how-to-chdir-using-c-in-linux-environment