3、目录I/O
文件IO与目录IO对比
目录IO | 文件IO |
---|---|
opendir 打开目录 | open 打开文件 |
mkdir 创建目录 | O_CREAT 或者使用create函数 |
readdir 读目录 | read读文件 |
closedir 关闭目录 | close关闭文件 |
3.1 创建目录 mkdir函数
#include <sys/stat.h>
#include <sys/types.h>
int mkdir(const char *pathname, mode_t mode);
成功返回0 失败返回 -1
3.2 打开目录
#include <sys/types.h>
#include <dirent.h>
DIR *opendir(const char *name);
DIR *fdopendir(int fd);
成功返回DIR指针 失败返回NULL
DIR 结构体的原型为:struct_dirstream
在linux系统中:
typedef struct __dirstream DIR;
struct __dirstream
{
void *__fd; /* `struct hurd_fd' pointer for descriptor. */
char *__data; /* Directory block. */
int __entry_data; /* Entry number `__data' corresponds to. */
char *__ptr; /* Current pointer into the block. */
int __entry_ptr; /* Entry number `__ptr' corresponds to. */
size_t __allocation; /* Space allocated for the block. */
size_t __size; /* Total valid data in the block. */
__libc_lock_define (, __lock) /* Mutex lock for this structure. */
};
3.3 关闭目录
#include <sys/types.h>
#include <dirent.h>
int closedir(DIR *dirp);
3.4 读取目录
#include <dirent.h>
struct dirent *readdir(DIR *dirp);
成功返回指针, 若在目录尾或出错返回NULL
struct dirent {
ino_t d_ino; /* Inode number */
off_t d_off; /*从目录开始到当前目录的距离 */
unsigned short d_reclen; /* Length of this record */
unsigned char d_type; /* Type of file; not supported
by all filesystem types */
char d_name[256]; /* Null-terminated filename */
};
主要关注 ino_t d_ino d_name[256]
对于每一个目录来说 就相当于一个链表
当前目录下的文件就是链表中的一个个节点
当使用readdir读取之后,链表指针便向后移动
DIR *dp;
struct dirent * dir;
dp = opendir("/home/now/linux-c");
if (dp == NULL)
{
perror("opendir");
return -1;
}
while(1)
{
dir = readdir(dp);
if (dir == NULL) //读到目录尾,或出错
break;
else
printf("%s\n",dir->d_name);
}
综合练习 实现 文件的上传与下载
#include<stdio.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
/*
*文件上传与下载
*下载、进入指定的目录,然后获取相应的文件
上传 将当前路径下的文件上传至 指定目录下
*
* */
int main(int argc,char *argv[])
{
DIR * dp;
struct dirent *dir;
char path[128]={0};
char file_name[128]={0};
char buf[512]={0};
int ret = 1;
// fgets(str, sizeof(str), stdin);
//去掉'\n'
printf("输入指定的目录路径\n");
scanf("%s", path);
dp = opendir(path); //打开指定目录
if (dp == NULL)
{
perror("opendir");
return -1;
}
while(1)
{
dir = readdir(dp); //读取该目录下的子文件
if (dir == NULL)
break;
else
printf("%s\n", dir->d_name);
}
printf("输入需要下载的文件\n");
scanf("%s", file_name);
char file_path[256]={0};
sprintf(file_path,"%s/%s", path, file_name);
int fd_source = open(file_path, O_RDWR);
if (fd_source == -1)
{
perror("open");
return -1;
}
int fd_target = open(file_name, O_RDWR | O_CREAT, 0777);
if (fd_target == -1)
{
perror("open");
return -1;
}
while (ret)
{
ret = read(fd_source, buf, 512);
write(fd_target, buf, ret);
}
close(fd_source);
close(fd_target);
closedir(dp);
return 0;
}