一个程序猿的奋斗史程序员首页推荐

C语言学习13.文件夹和目录操作

2017-10-28  本文已影响20人  快乐的提千万

目录的操作:

获取当前目录(getcwd)
char cwd[300];
getcwd(cwd,sizeof(cwd));
设置当前目录(chdir)
chdir("/home");
创建目录(mkdir)
mkdir("test",0751);
删除目录(rmdir,remove)
rmdir("test");
读取目录:
opendir,readdir,closedir,主要用于遍历目录。

#include<unistd.h>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<sys/types.h>
#include<dirent.h>

//列出某个目录下的文件列表以及相应 i 节点号,并且当遇到子目录,在其后面标示“(DIR)”字样。
int main()
{
    DIR *dp;
    struct dirent *dirp;
    char dirname[]="./";
    if((dp=opendir(dirname))==NULL){
        perror("opendir error");
        exit(1);
    }
    while((dirp=readdir(dp))!=NULL){
        if((strcmp(dirp->d_name,".")==0)||(strcmp(dirp->d_name,"..")==0))
            continue;
        printf("%6d:%-19s %5s\n",dirp->d_ino,dirp->d_name,(dirp->d_type==DT_DIR)?("(DIR)"):(""));
    }
    return 0;
}

文件夹遍历:

#include<unistd.h>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<sys/types.h>
#include<dirent.h>
#include <sys/stat.h>
#include <unistd.h>

//传入路径即可
void show_all(const char* path)
{

    DIR* dirp=opendir(path); //类似于FILE
    struct dirent* de=NULL; //dirent 获取文件夹目录属性
    struct stat st; //stat 获取文件属性
    char path2[500];
    while(de=readdir(dirp))
    {
        if(strcmp(de->d_name,".")==0 || strcmp(de->d_name,"..")==0) continue;
        printf("%s\n",de->d_name);
        strcpy(path2,path);
        strcat(path2,"/");
        strcat(path2,de->d_name);
        stat(path2,&st);
        if(S_ISDIR(st.st_mode))
        {
            show_all(path2);
        }
    }
    closedir(dirp);
}
上一篇下一篇

猜你喜欢

热点阅读