Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/docker/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
LinuxC读取目录_C_Linux_Directory - Fatal编程技术网

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()
直接调用系统调用