linux -> C/C++ 目录操作

来源:互联网 发布:iPad看视频软件 编辑:程序博客网 时间:2024/06/08 06:42

创建/删除目录

#include<sys/stat.h>int mkdir(const char *path_name,mode_t mode);
#include<unistd.h>int rmdir(const char *path_name);

rmdir要求删除的目录为空目录,当目录非空时会操作失败

目录文件的打开/关闭/读取

#include<dirent.h>DIR *opendir(const char *path_name);  //打开目录int closedir(DIR *dp);   //关闭目录struct dirent *readdir(DIR *dp); //读取目录

读取目录的示例代码

#include <stdio.h>#include <fcntl.h>#include <sys/stat.h>#include <unistd.h>#include <dirent.h>#include <sys/types.h>#include <time.h>int main(){    struct stat statbuf;    DIR *dir=opendir("testdir");    dirent* dip;    while ((dip = readdir(dir))!=NULL)    {           lstat(dip->d_name, &statbuf);        printf("%s , %s\n", dip->d_name,   ctime(&statbuf.st_atime));    }    return 0;}

当前工作路径

#include<unistd.h>int chdir(const char *path_name);   //切换工作路径int fchdir(int fd);  //切换工作路径char * getcwd(char*buf,size_t size);  //获取当前目录路径(绝对路径)

示例代码

#include <stdio.h>#include <fcntl.h>#include <unistd.h>#include <dirent.h>int main(){    int res = chdir("testdir");    if (res==-1)    {        printf("cd dir falid!");    }    else    {        char npath[200];                getcwd(npath,200);        printf("%s\n", npath);    }    return 0;}
原创粉丝点击