如何在Linux环境下使用C chdir

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13204650/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 17:41:14  来源:igfitidea点击:

How to chdir using C in Linux environment

clinuxchdir

提问by user1795444

I am new in c programming. How can I change directory like /home/jobs/$ans/xxx/while I have $ansis a user string I can't chdirin c program.

我是 C 编程的新手。我如何更改目录,就像/home/jobs/$ans/xxx/我拥有$ans的用户字符串一样,我无法chdir在 c 程序中使用它。

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?

如何更改目录chdir

回答by solarised

Use something like:

使用类似的东西:

char jdir[200]
scanf("%s", &jdir);
char blah[200];
snprintf(blah, 199, "/home/jobs/%s/xxx", jdir);
chdir(blah);

回答by zwol

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:

用 C 编写这个程序似乎有点愚蠢,但如果有充分的理由这样做(例如,如果它必须是 setuid),那么你应该更加谨慎。我会做这样的事情:

#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] = '##代码##'; /* 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.

这个答案的编辑历史将证明让这个 100% 正确是多么困难 - 我不断回到它并意识到我忘记了另一个需要辩护的案例。