目录属性操作
chdir
int chdir(const char *path);
path: 切换的路径
getcwd
#include <unistd.h>
char *getcwd(char *buf, size_t size);
参数:
buf: 缓冲区, 存储当前的工作目录
size: 缓存区大小
返回值:
成功: 当前的工作目录
失败: NULL
#include <stdio.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char const *argv[])
{
if (argc < 2) {
printf("a.out dir\n");
}
int ret = chdir(argv[1]);
if (ret == -1) {
perror("chdir");
exit(1);
}
int fd = open("char.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;
}
mkdir
int mkdir(const char *pathname, mode_t mode);
参数:
pathname: 创建的目录名
mode: 目录权限, 八进制的数, 实际权限: mode & ~umask
rmdir
int rmdir(const char *pathname);
opendir
DIR *opendir(const char *name);
readdir
struct dirent *readdir(DIR *dirp);
struct dirent {
ino_t d_ino; // 此目录进入点的inode
off_t d_off; // 目录文件开头至此目录进入点的位移
unsigned short d_reclen; ///d_name的长度, 不包含NULL字符
unsigned char d_type; // d_name所指的文件类型
char d_name[256]; // 文件名
};
DT_BLK This is a block device.
DT_CHR This is a character device.
DT_DIR This is a directory.
DT_FIFO This is a named pipe (FIFO).
DT_LNK This is a symbolic link.
DT_REG This is a regular file.
DT_SOCK This is a UNIX domain socket.
DT_UNKNOWN The file type is unknown.
closedir
int closedir(DIR *dirp);