实验十一
实验名称:
文件系统编程
实验要求:
1. 编写一个程序,实现将一个目录的所有内容复制到另一个目录的功能。要求:
源文件(目录)和目标文件(目录)的属主、权限等信息保持一致; 每复制一个文件(目录),在屏幕提示相应信息;
当遇到符号链接文件时,显示该文件为链接文件,不复制。
流程图: 开始 输入源目录 否 输入正确? 是 输入目标目 否 是否存在? 是 创建目录 开始复制 否 否 链接文件? 普通文件? 目录文件? 是 是 是 复制文件 是 改变文件权限 最后一个? 否 下一个文件 结束 否
代码:
#include
char paths[1000],patht[1000],temp_paths[1000],temp_patht[1000]; void Copy(char *spathname,char *tpathname) {
int sfd,tfd; struct stat s,t; char c;
sfd=open(spathname,O_RDONLY);
tfd=open(tpathname,O_RDWR|O_CREAT); while(read(sfd,&c,1)>0) write(tfd,&c,1); fstat(sfd,&s);
chown(tpathname,s.st_uid,s.st_gid); chmod(tpathname,s.st_mode); close(sfd); close(tfd); }
void d_copy(char *spathname,char *tpathname) {
struct stat s,t,temp_s,temp_t; struct dirent *s_p; DIR *dirs,*dirt; stat(spathname,&s);
mkdir(tpathname,s.st_mode);
chown(tpathname,s.st_uid,s.st_gid); dirt=opendir(tpathname); dirs=opendir(spathname);
strcpy(temp_paths,spathname); strcpy(temp_patht,tpathname); while((s_p=readdir(dirs))!=NULL) {
if(strcmp(s_p->d_name,\{
strcat(temp_paths,\
strcat(temp_paths,s_p->d_name); strcat(temp_patht,\
strcat(temp_patht,s_p->d_name); lstat(temp_paths,&s); temp_s.st_mode=s.st_mode; if(S_ISLNK(temp_s.st_mode)) {
printf(\}
else if(S_ISREG(temp_s.st_mode)) {
printf(\Copy(temp_paths,temp_patht); strcpy(temp_paths,spathname); strcpy(temp_patht,tpathname); }
else if(S_ISDIR(temp_s.st_mode)) {
printf(\d_copy(temp_paths,temp_patht); strcpy(temp_paths,spathname); strcpy(temp_patht,tpathname); } } }
}
int main() {
struct dirent *sp,*tp;
char spath[1000],tpath[1000],temp_spath[1000],temp_tpath[1000]; struct stat sbuf,tbuf,temp_sbuf,temp_tbuf; char sdirect[1000],tdirect[1000],judge; DIR *dir_s,*dir_t;
printf(\scanf(\dir_s=opendir(sdirect); if(dir_s==NULL) {
printf(\return 0; }
if(stat(sdirect,&sbuf)!=0) {
printf(\return 0; }
printf(\scanf(\dir_t=opendir(tdirect); if(dir_t==NULL) {
mkdir(tdirect,sbuf.st_mode);
chown(tdirect,sbuf.st_uid,sbuf.st_gid); dir_t=opendir(tdirect); } else {
chmod(tdirect,sbuf.st_mode);
chown(tdirect,sbuf.st_uid,sbuf.st_gid); }
strcpy(spath,sdirect); strcpy(tpath,tdirect);
strcpy(temp_spath,sdirect); strcpy(temp_tpath,tdirect);
printf(\while((sp=readdir(dir_s))!=NULL) {
if(strcmp(sp->d_name,\{
strcat(temp_spath,\
strcat(temp_spath,sp->d_name); strcat(temp_tpath,\
strcat(temp_tpath,sp->d_name); lstat(temp_spath,&sbuf);
temp_sbuf.st_mode=sbuf.st_mode; if(S_ISLNK(temp_sbuf.st_mode)) {
printf(\}
else if((S_IFMT&temp_sbuf.st_mode)==S_IFREG) {
printf(\Copy(temp_spath,temp_tpath); strcpy(temp_tpath,tpath); strcpy(temp_spath,spath); }
else if((S_IFMT&temp_sbuf.st_mode)==S_IFDIR) {
printf(\d_copy(temp_spath,temp_tpath);
strcpy(temp_tpath,tpath); strcpy(temp_spath,spath); } }
}
printf(\closedir(dir_t); closedir(dir_s); return 1; }
运行效果: