Copyright © 2024 Squareroot_2, All rights reserved.
实验四 复制文件
一、实验目的
通过设计实现一个文件复制程序,熟悉Linux文件系统提供的有关文件操作的系统调用。文件系统是使用计算机信息系统的重要接口,通过使用文件系统的系统调用命令操作文件,以达到对文件系统实现功能的理解和掌握。
二、实验内容
在Linux平台上,完成一个目录复制命令mycp,复制包括目录下的文件和子目录。
三、程序设计与实现
实验环境:Ubuntu 20.04
程序源码:mycp.cpp
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<sys/time.h>
#include<fcntl.h>
#include<string.h>
#include<dirent.h>
#include<utime.h>
#define ReadSize 1024
#define LinkPathLen 1024
//将文件从旧路径复制到新路径
void copyFile(char* oldPath, char* newPath){
struct stat statbuf; //文件属性信息
struct utimbuf uTime; //文件的最后修改和访问时间信息
int oldfd, newfd; //新旧文件的描述符
int size = 0; //每次从文件中读取的数据量
char buffer[ReadSize]; //保存数据的缓冲区
memset(buffer, 0, sizeof(buffer));
//获取旧文件信息,创建新文件
stat(oldPath, &statbuf);
newfd = creat(newPath, statbuf.st_mode);
//打开文件
if ((oldfd = open(oldPath, O_RDONLY)) < 0) {
printf("open file:%s error!\n", oldPath);
exit(-1);
}
//复制文件内容
while ((size =