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;
}
You need to check in your case that args[1]
is both set and refers to an actual directory. A sample run, with tmp
is a subdirectory off my current directory but you can use any valid directory, gives me:
testprog tmp
[.]
[..]
[file1.txt]
[file1_file1.txt]
[file2.avi]
[file2_file2.avi]
[file3.b.txt]
[file3_file3.b.txt]
Note also that you have to pass a directory in, not a file. When I execute:
testprog tmp/file1.txt
I get:
Cannot open directory 'tmp/file1.txt'
That's because it's a file rather than a directory (though, if you're sneaky, you can attempt to use diropen(dirname(argv[1]))
if the initial 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.
opendir
returns aDIR *
. It returns NULL in 2 situations: the directory couldn't be accessed or memory couldn't be allocated to hold the result. – Compagnie/root/TEST
is either not a directory or you do not have permissions to search through it. Try run your code using/tmp
or.
as the directory. – Caputtoopendir
in that previous comment rather thanopen
. What doesls -ald /root /root/TEST
output? – Caputto/dir1/dir2
thencd .
will leave you there andcd ..
will take you to/dir1
. (and keep in mind if you want to talk to someone specific, use the '@paxdiablo' text somewhere in your comment - that way the user gets notified). – Caputto