zoukankan      html  css  js  c++  java
  • 目录文件的操作函数 mkdir ,opendir,readdir,closedir

    1.  int mkdir(const char *pathname, mode_t mode);   头文件 :<sys/stat.h>  <sys/types.h>

    功能:创建一个目录
    参数:pathname:目录的路径名
    mode:目录的权限(可读,可写,可执行)
    返回值:成功返回0,失败返回-1

    2.   DIR *opendir(const char *name);      头文件 :<sys/types.h>    <dirent.h>

    功能:获得目录流
    参数:要打开的目录
    返回值:成功:目录流  ;失败:NULL

    3.   struct dirent *readdir(DIR *dirp);   头文件 :<dirent.h>
    功能:读目录
    参数:要读的目录流
    返回值:成功返回结构体指针,失败返回NULL

    4.   int closedir(DIR *dirp);        头文件 :<dirent.h>  <sys/types.h> 
    功能:关闭目录流
    参数:目录流
    返回值:成功0 ;失败-1

     

    例子:通过上述函数实现 shell 中的 ls 功能

    #include <stdio.h>
    #include <stdlib.h>
    #include <sys/types.h>
    #include <dirent.h>
    int main(int argc, const char *argv[])
    {
        mkdir("./test",0666);//在当前路径下,创建一个目录  目录权限0666
    //    DIR *opendir(const char *name);
        DIR *dir = NULL;
        dir = opendir("./");//打开一个目录,成功返回路径名
        if(dir == NULL)
        {
            perror("opendir fail : ");
            exit(1);
        }
        
    //  struct dirent *readdir(DIR *dirp);
        struct dirent * ret = NULL;
       
        
    #if 1  //循环读,直到读完当前目录下的内容
        int i=0;
        while(1)
        {
            ret = readdir(dir);//读取这个目录,返回 DIR *指针,目录流
            if(ret == NULL)
            {
                break;
                perror("read fail : ");
            }
            //  去除 . 和 ..隐藏文件
            if( strcmp(ret->d_name,".")==0 || strcmp(ret->d_name,"..")==0 ) 
            { 
                continue;
            }
            i++;
            printf("[%d] %s
    ",i,ret->d_name);    
        }
    #endif
        closedir(dir);//关闭
        return 0;
    }

    测试:

  • 相关阅读:
    HDU 4864 Task(经典贪心)
    51Nod
    POJ 3122 Pie(二分+贪心)
    HDU 1053 Entropy(哈夫曼编码 贪心+优先队列)
    POJ 1328 Radar Installation(很新颖的贪心,区间贪心)
    11572
    HDU 1789 Doing Homework again(非常经典的贪心)
    合并果子(贪心+优先队列)
    CSU-ACM2018暑假集训6—BFS
    HDU 2102 A计划(两层地图加时间限制加传送门的bfs)
  • 原文地址:https://www.cnblogs.com/electronic/p/10920114.html
Copyright © 2011-2022 走看看