Open directory using C

后端 未结 4 1324
时光取名叫无心
时光取名叫无心 2020-12-03 01:55

I am accepting the path through command line input.

When I do

dir=opendir(args[1]);

it doesn\' t enter the loop...i.e dir==nu

4条回答
  •  渐次进展
    2020-12-03 02:10

    You should really post your code(a), but here goes. Start with something like:

        #include 
        #include 
    
        int main (int argc, char *argv[]) {
            struct dirent *pDirent;
            DIR *pDir;
    
            // Ensure correct argument count.
    
            if (argc != 2) {
                printf ("Usage: testprog \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.

提交回复
热议问题