Linux C read a directory

2019-09-07 05:26发布

问题:

Hello I want to read from and write to a directory just like reading from and writing to files. I always use the open, read, write and close functions, which means I use descriptors. But doing this on a directory doesn't work, the open call works, but read returns -1 and errno is EISDIR. Am I forced to use streams to read a directory?

回答1:

The read() and write() system calls cannot be used on directories. Instead, the getdents() / getdents64() system calls are used to read a directory. Directories cannot be directly written at all.

Futhermore, glibc does not provide a wrapper for the getdents() / getdents64() system calls - instead it provides the POSIX-conforming readdir() function, which is implemented using those system calls. Most programs should use readdir(), but it is possible to call the system calls directly using syscall().



回答2:

I found this code here in Stack Overflow (How can I get the list of files in a directory using C or C++?), that helped me a lot in understanding how it works:

#include <dirent.h>
#include <stdio.h>
#include <string.h>

int main(){
    DIR* dirFile = opendir( "." );
    struct dirent* hFile;
    if ( dirFile ) 
    {
    while (( hFile = readdir( dirFile )) != NULL ) 
    {
       if ( !strcmp( hFile->d_name, "."  )) continue;
       if ( !strcmp( hFile->d_name, ".." )) continue;

     // in linux hidden files all start with '.'
       if ( gIgnoreHidden && ( hFile->d_name[0] == '.' )) continue;

     // dirFile.name is the name of the file. Do whatever string comparison 
     // you want here. Something like:
        if ( strstr( hFile->d_name, ".c" ))
           printf( "found an .txt file: %s", hFile->d_name );
    } 
  closedir( dirFile );
 }
}