unix下面目录的详细操作(包括实现给定目录遍历下面所有文件)



unix下面目录的详细操作(包括实现给定目录遍历下面所有文件)
 
与目录相关的有:
  www.2cto.com  
#include<dirent.h>
(1)DIR *opendir(const char *pathname);
打开一个目录,并且返回一个DIR类型的指针
(2)struct dirent *readdir(DIR *dp);
读一个目录并且返回一个dirent类型的指针。
(3)void rewinddir(DIR *dp);
(4)long telldir(DIR *dp);
(5)void seekdir(DIR *dp,long loc);
 
与目录操作有关的结构体有:
dirent结构体:
struct dirent {
ino_t d_ino; /* 索引号 */
off_t d_off; /* 下一个偏移量 */
unsigned short d_reclen; /* 本记录长度 */
unsigned char d_type; /* 文件类型 */
char d_name[256]; /* 文件名 */
};
  www.2cto.com  
DIR结构体
struct __dirstream
  {
    void *__fd;                        /* `struct hurd_fd' pointer for descriptor.  */
    char *__data;                /* Directory block.  */
    int __entry_data;                /* Entry number `__data' corresponds to.  */
    char *__ptr;                /* Current pointer into the block.  */
    int __entry_ptr;                /* Entry number `__ptr' corresponds to.  */
    size_t __allocation;        /* Space allocated for the block.  */
    size_t __size;                /* Total valid data in the block.  */
    __libc_lock_define (, __lock) /* Mutex lock for this structure.  */
  };
typedef struct __dirstream DIR;
 
应用上面的所有知识可以解决有关目录操作的所有问题了。下面写了一个简单的程序来说明相关函数的应用:
 
题目:给定一个目录,然后遍历目录下面所有的文件,并打印文件名
 
#include<dirent.h>
 
#include<stdio.h>
int main(int argc,char **argv)
{  www.2cto.com  
   DIR *dirp;
   struct dirent *direntp;
 
   if(argc!=2)
   {
       printf("formant error!\n");
   }
   
   dirp=opendir(argv[1]);
   while((direntp=readdir(dirp))!=NULL)
     {
          printf("%s\n",direntp->d_name);
     }
   close(dirp);
   exit(0);
}
 
 
作者 liangxanhai

相关内容

    暂无相关文章