目录IO
文件 IO 和目录 IO 的对比:
区别:
之前我们学习的文件 IO 和提到过的标准 IO 都是对文件操作, 接下来学习的目录 IO 都是对目录操作。
mkdir
创建目录函数如下表所示:
代码
mkdir.c
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
int main(int argc, char const *argv[])
{
int ret;
if(argc != 2)
{
printf("Usage: %s <name file>\n", argv[0]);
return -1;
}
ret = mkdir(argv[1], 0666);
if(ret < 0)
{
printf("mkdir is error!!!\n");
return -2;
}
printf("mkdir is ok!!!\n");
return 0;
}
运行结果
opendir/closedir
代码
mkdir.c
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
int main(int argc, char const *argv[])
{
int ret;
DIR *dp;
dp = opendir(argv[1]);
if(dp != NULL)
{
printf("opendir is ok!!!\n");
}
closedir(dp);
return 0;
}
运行结果
readdir
代码
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
int main(int argc, char const *argv[])
{
int ret;
DIR *dp;
struct dirent *dir;
dp = opendir(argv[1]);
if (dp == NULL)
{
printf("opendir is error!!!\n");
return -1;
}
printf("opendir is ok!!!\n");
while (1)
{
dir = readdir(dp);
if (dir != NULL)
{
printf("file name is %s\n", dir->d_name);
}else
{
break;
}
}
closedir(dp);
return 0;
}
运行结果
综合练习
需求:
1.打印我们要拷贝的目录下的所有文件名, 并拷贝我们需要的文件。
2.通过键盘输入我们要拷贝的文件的路径和文件名等信息
代码
practice.c
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
int main(int argc, char const *argv[])
{
DIR *dir;
struct dirent *rdir;
int fd_src, fd_obj;
ssize_t ret;
char buf[100] = {0};
char file_path[32]={0};
char file_name[32]={0};
printf("please enter the file path:\n");
scanf("%s", file_path);
dir = opendir(file_path);
if (dir == NULL)
{
printf("opendir is error!!!\n");
return -2;
}
printf("opendir is ok!!!\n");
while (1)
{
rdir = readdir(dir);
if (rdir != NULL)
{
printf("filename: %s\n", rdir->d_name);
}
else
{
break;
}
}
printf("please enter the file name:\n");
scanf("%s", file_name);
fd_src = open(strcat(strcat(file_path, "/"), file_name), O_RDONLY);
fd_obj = open(file_name, O_CREAT | O_WRONLY, 0666);
if (fd_src < 0 || fd_obj < 0)
{
printf("open is error!!!\n");
return -3;
}
while ((ret = read(fd_src, buf, 32)) != 0)
{
write(fd_obj, buf, ret);
}
close(fd_obj);
close(fd_src);
closedir(dir);
return 0;
}