linux 系统调用实现文件拷贝

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;
}

运行效果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值