You should really post your code(a), but here goes. Start with something like:
#include <stdio.h>
#include <dirent.h>
int main (int argc, char *argv[]) {
struct dirent *pDirent;
DIR *pDir;
// Ensure correct argument count.
if (argc != 2) {
printf ("Usage: testprog <dirname>\n");
return 1;
}
// Ensure we can open directory.
pDir = opendir (argv[1]);
if (pDir == NULL) {
printf ("Cannot open directory '%s'\n", argv[1]);
return 1;
}
// Process each entry.
while ((pDirent = readdir(pDir)) != NULL) {
printf ("[%s]\n", pDirent->d_name);
}
// Close directory and exit.
closedir (pDir);
return 0;
}
您需要检查您的情况args[1]
既已设置又引用实际目录。示例运行,tmp
是我当前目录之外的子目录,但您可以使用任何有效的目录,给我:
测试程序临时文件
[.]
[..]
[file1.txt]
[file1_file1.txt]
[file2.avi]
[file2_file2.avi]
[file3.b.txt]
[file3_file3.b.txt]
另请注意,您必须通过目录在,不是一个file.当我执行时:
testprog tmp/file1.txt
I get:
Cannot open directory 'tmp/file1.txt'
这是因为它是一个文件而不是一个目录(不过,如果你偷偷摸摸,你可以尝试使用diropen(dirname(argv[1]))
如果初始的diropen
fails).
(a) This has now been rectified but, since this answer has been accepted, I'm going to assume it was the issue of whatever you were passing in.