Open directory using C

后端 未结 4 1323
时光取名叫无心
时光取名叫无心 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:28

    Some feedback on the segment of code, though for the most part, it should work...

    void main(int c,char **args)
    
    • int main - the standard defines main as returning an int.
    • c and args are typically named argc and argv, respectfully, but you are allowed to name them anything

    ...

    {
    DIR *dir;
    struct dirent *dent;
    char buffer[50];
    strcpy(buffer,args[1]);
    
    • You have a buffer overflow here: If args[1] is longer than 50 bytes, buffer will not be able to hold it, and you will write to memory that you shouldn't. There's no reason I can see to copy the buffer here, so you can sidestep these issues by just not using strcpy...

    ...

    dir=opendir(buffer);   //this part
    

    If this returning NULL, it can be for a few reasons:

    • The directory didn't exist. (Did you type it right? Did it have a space in it, and you typed ./your_program my directory, which will fail, because it tries to opendir("my"))
    • You lack permissions to the directory
    • There's insufficient memory. (This is unlikely.)

提交回复
热议问题