linux 系统调用实现文件拷贝
copyfile程序如下:
#include<iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>
#include<string>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/wait.h>
using namespace std;
void CoypFile(string sourceFile, string objFile)
{
int fd1 = 0;//源文件描述符
int fd2 = 0;//目标文件描述符
struct flock lock;//文件锁结构体
memset(&lock, 0, sizeof(struct flock));
lock.l_start = 0;
lock.l_whence = SEEK_SET;
lock.l_len = 0;
ssize_t r_size;//读文件返回长度
char buffer[10] = { 0 };
fd1 = open(sourceFile.c_str(), O_RDWR);//打开源文件 只读
fd2 = open(objFile.c_str(), O_CREAT | O_RDWR, 0777);//打开目标文件 没有就创建
//判断文件是否正常打开
if (fd1 < 0)
{
perror("open fail");
return;
}
else
{
if (fcntl(fd2, F_GETLK, &lock) == 0)//调用成功返回0
{
if (lock.l_type == F_WRLCK)
{
cout << "已经有写锁" << endl;
}
else if (lock.l_type != F_WRLCK)//不是写锁 设置写锁
{
lock.l_type = F_WRLCK;
if (fcntl(fd2, F_SETLK, &lock) == 0)//是否设置写锁成功
{
while ((r_size = read(fd1, buffer, sizeof(buffer))) > 0)
{
write(fd2, buffer, r_size);//读到的内容写到文件2
memset(buffer, 0x0, sizeof(buffer));
}
close(fd1);
close(fd2);
}
}
}
}
}
main()
{
CoypFile("/home/whb/projects/CopyFile/a", "/home/whb/projects/CopyFile/b");
return 0;
}
运行效果: