Linux 修仙之路
目录操作
1. getcwd 获取进程当前工作目录 (man 3 getcwd)
头文件包含及声明
#include <unistd.h>
char* getcwd(char* buf,size_t size);
成功:buf 保存当前进程工作目录位置
失败:NULL
2. chdir 改变当前进程的工作目录(man 2 chdir)
头文件包含及声明
#include<unistd.h>
int chdir(const char* path);
成功:0
失败:-1 并设置 errno
3. 文件、目录权限
Linux 所见皆文件,目录也是文件,其文件内容是该目录下所有子文件的目录项 dentry,vim 可打开目录文件
… | r | w | x |
---|---|---|---|
文件 | 文件的内容可以被查看 cat、more、less | 内容可以被修改 vi、> | 可以运行产生一个进程 ./文件名 |
目录 | 目录可以被浏览 ls、tree | 创建、删除、修改文件 mv、touch、mkdir | 可以被打开进入 cd |
4. opendir 打开一个目录(库函数 man 3 opendir)
头文件包含及函数声明
#include<sys/types.h>
#include<dirent.h>
DIR* opendir(const char* name);
*DIR 类似于 *FILE,参数支持相对路径和绝对路径
成功:指向该目录结构体指针
失败:返回NULL
5. closedir 关闭一个目录(man 3 readdir)
头文件包含及函数声明
#include<sys/types.h>
#include<dirent.h>
int closedir(DIR* dirp)
6. readdir 读一个目录(man 3 readdir)
#include<dirent.h>
struct dirent* readdir(DIR* dirp);
成功:返回目录项的结构体
失败:NULL errno不改变
目录结构体:
- d_ino:Inode 号
- d_name[256]: 文件名字
7. demo 实现 ls 的功能
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
#include<dirent.h>
#include<errno.h>
/* 实现 ls 的功能 */
int main(int argc, char * argv [ ])
{
DIR* dp;
struct dirent *sdp;
dp = opendir(argv[1]);
if (dp == NULL)
{
perror("opendir error\n");
exit(1);
}
while ((sdp = readdir(dp) )!= NULL)
{
/* 排除. 和.. */
if (strcmp(sdp->d_name,".") == 0)
continue;
printf("%s\t", sdp->d_name);
}
printf("\n");
closedir(dp);
return 0;
}
结果展示:
成功!!