使用C打开目录

Vin*_*d K 14 c opendir

我通过命令行输入接受路径.

当我做

dir=opendir(args[1]);
Run Code Online (Sandbox Code Playgroud)

它没有进入循环......即dir==null......

如何将命令行输入传递给dir指针?

void main(int c,char **args)
{
    DIR *dir;
    struct dirent *dent;
    char buffer[50];
    strcpy(buffer, args[1]);
    dir = opendir(buffer);   //this part
    if(dir!=NULL)
    {
        while((dent=readdir(dir))!=NULL)
            printf(dent->d_name);
    }
    close(dir);
}

./a.out  /root/TEST is used to run the program..
./a.out --> to execute the program
/root/TEST --> input by the user i.e valid path
Run Code Online (Sandbox Code Playgroud)

pax*_*blo 39

你应该真的发布你的代码,但是这里.从...开始:

    #include <stdio.h>
    #include <dirent.h>

    int main (int c, char *v[]) {
        struct dirent *pDirent;
        DIR *pDir;

        if (c < 2) {
            printf ("Usage: testprog <dirname>\n");
            return 1;
        }
        pDir = opendir (v[1]);
        if (pDir == NULL) {
            printf ("Cannot open directory '%s'\n", v[1]);
            return 1;
        }

        while ((pDirent = readdir(pDir)) != NULL) {
            printf ("[%s]\n", pDirent->d_name);
        }
        closedir (pDir);
        return 0;
    }
Run Code Online (Sandbox Code Playgroud)

您需要检查args[1]已设置的案例并引用实际目录.当运行时:

testprog tmp
Run Code Online (Sandbox Code Playgroud)

(tmp是我当前目录的子目录,但你可以使用任何有效的目录),我得到:

[.]
[..]
[file1.txt]
[file1_file1.txt]
[file2.avi]
[file2_file2.avi]
[file3.b.txt]
[file3_file3.b.txt]
Run Code Online (Sandbox Code Playgroud)

请注意,您必须传入目录,而不是文件.当我执行:

testprog tmp/file1.txt
Run Code Online (Sandbox Code Playgroud)

我明白了:

Cannot open directory 'tmp/file1.txt'
Run Code Online (Sandbox Code Playgroud)

因为那是一个文件而不是一个目录(如果你偷偷摸摸,你可以尝试使用,diropen(dirname(v[1]))如果初始diropen失败).