第一题:预习 opendir 和 readdir函数
第二题:通过 opendir、readdir、write、read函数实现拷贝一个文件夹中的所有文件的功能(不考虑文件夹中还有文件夹的情况)
#include <myhead.h>
#include <sys/types.h>
#include <dirent.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[1], &buf);
mode_t mode = buf.st_mode;
if(S_ISDIR(mode) != 1)
{
fprintf(stderr,"目标文件不是一个目录\n");
return 1;
}
}
DIR *dp = opendir(argv[1]);
if(dp = NULL)
{
perror("opendir");
return 1;
}
while(1)
{
struct dirent *file = readdir(dp);
if(file == NULL){break;}
if(strcmp(file->d_name, ".") == 0 || strcmp(file->d_name, "..") == 0){continue;}
chdir(argv[1]);
int rfd = open(file->d_name, O_RDONLY);
chdir("..");
chdir(argv[2]);
int wfd = open(file->d_name, O_WRONLY | O_CREAT | O_TRUNC, 0666);
chdir("..");
while(1)
{
char buf[200] = {0};
int res = read(rfd, buf, 199);
if(res == 0){break;}
write(wfd, buf, strlen(buf));
}
close(rfd);
close(wfd);
}
closedir(dp);
return 0;
}