目录操作相关的函数
1.文件重命名
int rename(const char* oldpath,const char*newpath);
2.修改当前进程(应用程序)的路径
int chdir(const char*path);
参数:切换的路径
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char* argv[])
{
if(argc < 2)
{
printf("a.out dir\n");
exit(1);
}
int ret = chdir(argv[1]);
if(ret == -1)
{
perror("chdir");
exit(1);
}
int fd = open("chdir.txt", O_CREAT | O_RDWR, 0777);
if(fd == -1)
{
perror("open");
exit(1);
}
close(fd);
char buf[128];
getcwd(buf, sizeof(buf));
printf("current dir: %s\n", buf);
return 0;
}
3.获取当前进程的工作目录
char getcwd(charbuf,size_t size);
返回值:成功:当前的工作目录
失败:NULL参数:
buf:缓冲区,存储当前的工作目录
size:缓冲区的大小
4.创建目录mkdir
int mkdir(const char* pathname,mode_t mode);
参数:pathname:创建的目录名
mode:目录权限、八进制的数、实际权限:mode&~umask
5.删除一个空目录
int rmdir(const char * pathname)’
参数:空目录的名字
目录遍历函数介绍
1.打开一个目录
DIR *opendir(const char *name);
参数:目录名
返回值:指向目录的指针
2.读目录
struct dirent
{
ino_t d_ino; //此目录进入点的Inode
ff_t d_off; //目录文件开头至此目录进入点的位移
signed short int d_reclen; //d_name的长度,不包含NULL字符
unsigned char d_type; //d_name所指的文件类型
har d_name[256]; //文件名
};
d_typeDT_BLK 块设备
DT_CHR 字符设备
DT_DIR 目录
DT_LNK 软连接
DT_FIFO 管道
DT_REG 普通文件
DT_SOCK 套接字
DT_UNKNOWN 未知
struct dirent *readdir(DIR *dirp);
参数:opendir的返回值
返回值:目录项结构体
3.关闭目录
int closedir(DIR *dirp);
#读取指定目录下普通文件的个数
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <dirent.h>
int get_file_count(char* root)
{
DIR* dir;
struct dirent* ptr = NULL;
int total = 0;
char path[1024];
dir = opendir(root);
if(dir == NULL)
{
perror("opendir");
exit(1);
}
while((ptr = readdir(dir)) != NULL)
{
if(strcmp(ptr->d_name, ".") == 0 || strcmp(ptr->d_name, "..") == 0)
{
continue;
}
if(ptr->d_type == DT_DIR)
{
sprintf(path, "%s/%s", root, ptr->d_name);
total += get_file_count(path);
}
if(ptr->d_type == DT_REG)
{
total ++;
}
}
closedir(dir);
return total;
}
int main(int argc, char* argv[])
{
if(argc < 2)
{
printf("a.out path\n");
exit(1);
}
int total = get_file_count(argv[1]);
printf("%s has %d files!\n", argv[1], total);
return 0;
}