一、chdir函数:修改当前进程的路径 <unistd.h>,修改此函数所在进程的可执行程序的历经
int chdir(const char*path);
./a.out ../test/. 改变./a.out 进程所在的路径
二、getcwd函数:获取当前进程的工作路径
getcwd(buf, sizeof(buf));
三、mkdir函数 int mkdir(const char*str, mode_t mode); 此函数创建的目录需要给执行权限,否则打不开
四、rmdir函数:删除一个空目录
int rmdir(const char*pathname);
属于man第三章
五、opendir函数:打开一个目录
DIR *opendir(const char *name);
DIR *fopendir(int fd);
DIR结构指针,内部结构体,保存所打开目录的信息
六、readdir:读目录
struct dirent *readdir(DIR *ddirp); //返回一个记录文件信息的结构体
****opendir和readdir应用——递归读取目录中文件个数
Linux目录结构就是树状结构,遍历目录需用到递归
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <stdlib.h>
#include <string.h>
int getFileNum(char *path)
{
// open dirent
DIR *dir = NULL;
dir = opendir(path);
if(dir == NULL)
{
perror("opendir");
exit(1);
}
//遍历当前打开目录
struct dirent *ptr = NULL;
char tmpPath[1024] = {0};
int total = 0;
while((ptr = readdir(dir)) != NULL)
{
//过滤 . 和 ..
if(strcmp(ptr->d_name, ".") == 0 || strcmp(ptr->d_name, "..") == 0)
{
continue;
}
if(ptr->d_type == DT_DIR)
{
//递归读目录
sprintf(tmpPath, "%s/%s", path, ptr->d_name);
total += getFileNum(tmpPath);
}
//如果是普通文件
if(ptr->d_type == DT_REG)
{
total++;
}
}
closedir(dir); //获取完毕必须关闭目录,否则获取不到数目
return total;
}
int main(int argc, char **argv)
{
if(argc < 2)
{
printf("./a.out dir\n");
exit(1);
}
int total = getFileNum(argv[1]);
printf("%s has file numbers: %d\n", argv[1], total);
return 0;
}
七、文件描述符的复制(重定向)
dup和dup2函数:用来复制文件描述符
<unistd.h>
描述符复制:新分配一个文件描述符使得两个文件描述符指向同一个文件
int dup(int oldfd); //返回文件描述符中未被使用的最小的描述符
int dup2(int olddup, int newfd);
1、old——》new:如果new是一个被打开的文件描述符,再拷贝前先关闭new
2、old和new对应同一个文件描述符,不会关闭new,直接返回old
fcntl:改变已经打开文件的属性,在文件打开时,不许关闭文件属性就可以改变文件读写权限
现阶段学会:获得/设置文件状态标记
int fcntl(int fd, int cmd,long arg);
arg:一般为0