Linux 目录操作 fdopendir closedir readdir

//@@只有操作系统内核才有权限对目录进行写操作
#include <sys/types.h>
#include <dirent.h>


//打开目录
DIR *opendir(const char *name);
DIR *fdopendir(int fd);
RETURN VALUE
The opendir() and fdopendir() functions return a pointer to  the  directory  stream.
 On error, NULL is returned, and errno is set appropriately.


DIR是个内部的结构,函数用来保存正在被读的目录信息

//关闭目录
#include <sys/types.h>
#include <dirent.h>
int closedir(DIR *dirp);
returns 0 on success.  On error, -1 is returned
//目录读
struct dirent  *readdir(DIR *dp);
struct dirent {
               long  d_ino;              /* inode number */
               char  d_name[NAME_MAX+1]; /* filename (null-terminated) */
  }


参考程序:


//目录操作  打开目录输出目录中的文件 inode  名称
//code by JZ
#include<unistd.h>
#include<iostream>
#include<unistd.h>
#include<stdio.h>
#include<fcntl.h>
#include<dirent.h>
#include<limits.h>
#include<sys/stat.h>
using namespace std;
int main(int argc,char *argv[])
{

	DIR *dp;
	struct dirent* dirp;
	if(   ( dp=opendir(argv[1]) )==NULL  )
		return -1;
	while( ( dirp=readdir(dp) )!=NULL )
	{
		cout<<"i-node:"<<dirp->d_ino<<"  name:"<<dirp->d_name<<endl;
	}
	closedir(dp);
	return 0;
}




/*
[jz@localhost ~]$  g++ main.cpp 
[jz@localhost ~]$ ./a.out  /home/jz/

//结果:
i-node:789463  name:info
i-node:789671  name:.ICEauthority
i-node:791731  name:.bashrc
i-node:792177  name:main.cpp
i-node:792187  name:a.out
i-node:789459  name:man
i-node:792178  name:result
i-node:789704  name:.esd_auth
i-node:789648  name:Downloads
i-node:789683  name:.fontconfig
*/


你可能感兴趣的:(linux,redhat,centos,目录操作,fdopendir)