文章目录
一、目录操作函数
1. mkdir库函数
在指定路径下创建一个目录,参数mode指定了该目录的权限。如果目标目录已经存在,则报错File exists。创建成功返回0,如果失败则返回-1.
下面是mkdir库函数需要引入的头文件与函数声明。
#include <sys/stat.h>
#include <sys/types.h>
int mkdir(const char *pathname, mode_t mode);
2. rmdir库函数
删除指定路径下的空目录。删除成功返回0,否则返回-1.
下面是rmdir库函数需要引入的头文件与函数声明。
#include <unistd.h>
int rmdir(const char *pathname);
3. rename库函数
#include <stdio.h>
int rename(const char *oldpath, const char *newpath);
4.chdir库函数
改变当前进程的工作目录。成功返回0,否则返回-1.
#include <unistd.h>
int chdir(const char *path);
5. getcwd库函数
获取当前进程的工作目录,返回值与buf均为当前工作目录路径的字符串。
#include <unistd.h>
char *getcwd(char *buf, size_t size);
6.示例程序
在part06目录下创建了c程序文件,获取当前目录后并打印后,更改工作目录为在父目录下的目录part07,并在新的工作目录中创建test.txt文件。
#include <sys/stat.h>
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
int main()
{
char buf[64];
getcwd(buf, sizeof(buf));
printf("当前工作目录:%s\n", buf);
int ret = chdir("../part07");
if(ret == -1){
perror("chdir");
return -1;
}
getcwd(buf, sizeof(buf));
printf("修改后的工作目录:%s\n", buf);
ret = open("test.txt", O_CREAT | O_RDWR, 0664);
if(ret == -1){
perror("open");
return -1;
}
return 0;
}
二、目录遍历函数
1. opendir库函数
返回一个指向该目录下第一个文件的文件结构体指针。如果文件不能被打开或是打开失败,返回NULL。
#include <sys/types.h>
#include <dirent.h>
DIR *opendir(const char *name);
2.readdir库函数
返回下一个文件的指针。失败或是到达当前目录结尾,返回NULL。
#include <dirent.h>
struct dirent *readdir(DIR *dirp);
3. closedir库函数
关闭打开的文件目录。
#include <sys/types.h>
#include <dirent.h>
int closedir(DIR *dirp);
4. 示例程序
下面的程序实现了在终端给出目标文件夹路径,输出目标文件夹下普通文件(非文件夹)的个数
#include <sys/types.h>
#include <dirent.h>
#include <stdio.h>
#include <string.h>
int fileNumCount(char* path);
int main(int argc, char* argv[])
{
if(argc == 1){
printf("参数数量不足!\n");
return -1;
}
int ans = fileNumCount(argv[1]);
printf("%s 目录下普通文件个数:%d\n", argv[1], ans);
return 0;
}
int fileNumCount(char* path){
DIR* dirp = opendir(path);
int ans = 0;
struct dirent* p = readdir(dirp);
while(p){
if(p == NULL)
break;
if(strcmp(p->d_name, ".") == 0 || strcmp(p->d_name, "..") == 0){
;
}
//文件夹
else if(p->d_type == DT_DIR){
char* newPath = strcat(path, "/");
newPath = strcat(newPath, p->d_name);
ans += fileNumCount(newPath);
}
//普通文件
else{
ans++;
}
p = readdir(dirp);
}
closedir(dirp);
return ans;
}