一、 文件夹的系统函数
1.mkdir(),创建一个目录文件。
int mkdir(const char *pathname, mode_t mode);
第一个参数是路径,第二个参数是权限,一般为0777.
在shell命令中,使用mkdir可以创建一个目录,如果使用mkdir aa/bb/cc创建目录,而aa不存在时,可以使用mkdir aa/bb/cc -p;
如果使用mkdir函数来创建,需要一个一个的创建。
2.access()检查是否具有某些权限,是否存在,是否有读写运行的权限等。
int access(const char *pathname, int mode);
返回:如果具有这个权限返回0,没有或者异常返回-1.
3.opendir(),打开一个目录文件
DIR *opendir(const char *name);
DIR *fdopendir(int fd);
函数返回一个DIR的指针。
4.readdir();读取目录下面的文件
struct dirent *readdir(DIR *dirp);
返回的结果是一个结构体。
struct dirent {
ino_t d_ino; /* inode 编号 */
off_t d_off; /* offset to the next dirent */
unsigned short d_reclen; /* length of this record */
unsigned char d_type; /* type of file; not supported
by all file system types */
char d_name[256]; /* 文件名称*/
};
其中文件的类型有:1.DT_REG普通文件 2.DT_LIK符号链接 3.DT_DIR目录文件 4.DT_FIFO管道文件
如果返回NULL说明遍历完了。
例题:
1.使用系统调用完成mkdir实现建立xx/yy/zz
2.完成命令ls
3.完成文件夹的复制
一 、mkdir的实现。 #include <sys/stat.h> #include <sys/types.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <stdlib.h> //仿写mkdir命令 //输入的如果是x/y/z;而x并不存在,就会一个一个的创建 //核心是分割字符串 int main(int argc,char *argv[]) { argv[1]; //对argv[1]进行分割 char * p = strtok(argv[1],"/"); int erro = 0; char * path = (char *)malloc(256); strcpy(path,p); printf("%s\n",path); if(access(path,F_OK) != 0) { erro = mkdir(path ,0777); if(erro == -1) { perror("mkdir"); return -1; } } while(