What is the correct way to use the stat () function to check if a DIRENT is a directory or file?

I'm having problems with the if line (S_IFDIR (stbuf.st_mode)). Is this the right way to check the directory you want to fit into? The function at the moment seems to be doing it right for 1 or 2 cycles, and then crashing and segmentation errors.

I tried the following and probably more as a condition.

S_ISDIR(st_mode) ((st_mode & ST_IFMT) == S_IFDIR) S_IFDIR(stbuf.st_mode) 

I turned on the whole function because I am worried that the problem may be elsewhere.

 void getFolderContents(char *source, int temp){ struct stat stbuf; int isDir; dirPnt = opendir(source); if(dirPnt != NULL){ while(entry = readdir(dirPnt)){ char *c = entry->d_name; if(strcmp(entry->d_name, cwd) == 0 || strcmp(entry->d_name, parent) == 0){ } else{ stat(entry->d_name, &stbuf); printf("%i %i ", S_IFMT, stbuf.st_mode); if(S_IFDIR(stbuf.st_mode)){ //Test DIR or file printf("DIR: %s\n", entry->d_name); getFolderContents(entry->d_name, 0); } printf("FILE: %s\n", entry->d_name); } } closedir(dirPnt); } 
+4
source share
2 answers

Yes this is correct. But since you never go to a directory, you will not find it.

Consider the following directory hierarchy:

  a | +- b | | | +- c ... 

Your code scans the current directory and finds "a". It determines that it is a directory, and calls itself recursively and opens "a" for reading. It works. This scan will find a directory with the name "b", but trying to open it using the name of the entry will fail, since the path is now "a / b".

I recommend going to the directory (with chdir() ) before opening it. This means that you can simply opendir(".") . Save the old path and chdir() again when recursion is performed at that level (not earlier than making a recursive call to go deeper).

+3
source

Where is the record determined? is it a local variable? I don’t understand why it will be segfault, but maybe you should make it a local variable. One example where he will bite you is here:

  if(S_IFDIR(stbuf.st_mode)){ //Test DIR or file printf("DIR: %s\n", entry->d_name); getFolderContents(entry->d_name, 0); } printf("FILE: %s\n", entry->d_name); 

printf will print the wrong name, so you should add something else here.

The same thing happens with dirpnt. When you exit getFolderContents inside a while loop, you end up calling readdir on a closed dirpoint, which should take you out of the loop.

But, as Bahbar stated: You cannot overwrite and store a temporary variable in a global variable

+1
source

All Articles