LinuxC读取目录
你好,我想读和写一个目录,就像读和写文件一样。我总是使用LinuxC读取目录,c,linux,directory,C,Linux,Directory,你好,我想读和写一个目录,就像读和写文件一样。我总是使用打开、读取、写入和关闭功能,这意味着我使用描述符。但是在目录上执行此操作不起作用,open调用起作用,但是read返回-1,errno是EISDIR。我是被迫使用streams来读取目录的吗?我在Stack Overflow()中找到了这段代码,它帮助我了解了它的工作原理: #include <dirent.h> #include <stdio.h> #include <string.h> int ma
打开
、读取
、写入
和关闭
功能,这意味着我使用描述符。但是在目录上执行此操作不起作用,open
调用起作用,但是read
返回-1,errno
是EISDIR。我是被迫使用streams来读取目录的吗?我在Stack Overflow()中找到了这段代码,它帮助我了解了它的工作原理:
#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 );
}
}
#包括
#包括
#包括
int main(){
DIR*dirFile=opendir(“.”);
struct dirent*hFile;
if(dirFile)
{
而((hFile=readdir(dirFile))!=NULL)
{
如果(!strcmp(hFile->d_name,“.”)继续;
如果(!strcmp(hFile->d_name,“…”)继续;
//在linux中,所有隐藏文件都以“.”开头
如果(gIgnoreHidden&(hFile->d_name[0]=='.')继续;
//dirFile.name是文件名。请执行任何字符串比较
//你想要这里,比如:
if(strstr(hFile->d_name,“.c”))
printf(“找到一个.txt文件:%s”,hFile->d_name);
}
closedir(dirFile);
}
}
目录上不能使用read()
和write()
系统调用。相反,getdents()
/getdents64()
系统调用用于读取目录。目录根本无法直接写入
此外,glibc没有为getdents()
/getdents64()
系统调用提供包装器-相反,它提供了符合POSIX的readdir()
函数,该函数是使用这些系统调用实现的。大多数程序应该使用readdir()
,但是可以使用syscall()
直接调用系统调用