如何在Linux环境中使用C chdir [英] How to chdir using C in Linux environment
问题描述
我是C语言编程的新手.当我有 $ ans
是我不能 chdir
/home/jobs/$ ans/xxx/>在C程序中.
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.
我的脚本在下面:
#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);
}
如何使用 chdir
更改目录?
推荐答案
用C编写该程序似乎有些愚蠢,但是如果有充分的理由(例如,必须设置setuid),那么您应该对此更具防御性.我会做这样的事情:
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;
}
此答案的编辑历史将显示出100%正确的解决方法有多困难-我一直坚持下去,并意识到我忘记了另一件需要辩护的案件.
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.
这篇关于如何在Linux环境中使用C chdir的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!