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 );
}
}