思维导图:
预习 opendir 和 readdir函数
opendir函数:
DIR *opendir(const char *name);
参数name:要打开的目录名
返回值:成功返回指向DIR结构体的指针,失败返回NULL
readdir函数:
struct dirent *readdir(DIR *dirp);
参数dirp:opendir () 函数的返回值
返回值:函数调用成功,返回读到的文件的信息,目录文件被读完了或者函数调用失败返回 NULL 函数返回值 struct dirent 结构体原型如下:
struct dirent {
ino_t d_ino; /* Inode number */
off_t d_off; /* Not an offset; see below */
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 */
};
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 could not be determined.
通过 opendir、readdir、write、read函数实现拷贝一个文件夹中的所有文件的功能(不考虑文件夹中还有文件夹的情况)
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pthread.h>
#include <semaphore.h>
#include <wait.h>
#include <signal.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <semaphore.h>
#include <sys/msg.h>
#include <sys/shm.h>
#include <sys/un.h>
typedef struct sockaddr_in addr_in_t;
typedef struct sockaddr addr_t;
typedef struct sockaddr_un addr_un_t;
int main(int argc, const char *argv[])
{
if(access(argv[2],F_OK) == -1)//判断目标文件夹是否存在
{
mkdir(argv[2],0777);//不存在则创建目标文件夹
}else//如果存在,则需要判断该文件是否为目录文件
{
struct stat buf={0};
stat(argv[2],&buf);
mode_t mode=buf.st_mode;
if(S_ISDIR(mode) != 1)
{
fprintf(stderr,"该文件不是一个目录文件!\n");
return 1;
}
}
DIR* df=opendir(argv[1]);
if(dp == NULL)
{
perror("opendir");
return 1;
}
while(1)
{
struct dirent* dt=readdir(df);
if(dt == NULL)
{
break;
}
if(strcmp(dt->d_name,".")==0 || strcmp(dt->d_name,"..")==0)
{
continue;
}
chdir(argv[1]);//把工作目录切换到argv[1]里面
int rfd=open(dt->d_name,O_RDONLY);
if(rfd == -1)
{
perror("ropen");
}
chdir("..");//把工作目录切换到上一级目录
chdir(argv[2]);
int wfd=open(dt->d_name,O_WRONLY | O_CREAT | O_TRUNC,0666);
if(wfd == -1)
{
perror("wopen");
}
chdir("..");
while(1)
{
char s[16]={0};
int res=read(rfp,s,15);
if(res == 0)
{
breaak;
}
write(wfp,s,strlen(buf));
}
}
close(rfp);
close(wfp);
closedir(df);
return 0;
}