How to chdir using C in Linux environment

谁都会走 提交于 2019-12-08 10:46:33

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!