Linux I/O实现文件复制

前一段时间采用mmap实现了一个文件的复制操作,现在采用linux的I/O实现文件的复制,基本的思想是将文件复制到一个通用的buf中,然后将buf中的数据复制到新的文件中。这种方式比较容易理解,但是也是底层的系统调用,建议少用,但有时候必须采用(设备驱动)。

#include<stdio.h>
#include
#include
#include<stdlib.h>
#include
#include
 /*操作的基本权限*/
#define DEF_MODE S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH

int main()
{
        /*源文件*/
        int fdsrc = open("/home/gong/program/cprogram/Test.c",O_RDONLY,0);
        if(fdsrc==-1)
        {
                printf("error!!!\n");
                exit(-1);
        }

        /*获得源文件的大小*/
        struct stat statbuf;
        fstat(fdsrc,&statbuf);
        int length = statbuf.st_size;

        /*目的文件*/
        int fddst = open("/home/gong/program/cprogram/copydata.c",O_CREAT|O_RDWR,DEF_MODE);
        if(fddst==-1)
        {
                printf("error!!!\n");
                exit(-1);
        }
        
        /*实现基本的文件内容复制过程*/
        /*基本的思想就是将数据首先复制到一个大小合适的buf中,然后将buf其中的内容写到给文件2*/
/*每一次都读入buf中,然后写buf的数据到文件2中*/
        char buf[1024];/*buf大小*/
        char *p = buf;/*指向buf的指针*/
        /*长度统计*/
        int rlength=0,Rlength = 0;                                                        
        int wlength=0;

        while(length > 0)
        {
                /*先读后先的过程*/
                rlength = read(fdsrc,p,1024);
                Rlength = rlength;
                while(rlength > 0)/*确保每次读出来的全部写入到文件中*/
                {
                        wlength = write(fddst,p,rlength);
                        rlength -= wlength;/*检测还有多少没有被复制*/
                        p += wlength;/*移动指针到没有写入的区域*/
                }
                p = buf;/*确保每次都是复制到buf中*/
                length -= Rlength;
        }

        /*关闭文件*/
        close(fdsrc);
        close(fddst);
        exit(0);
}
编译调试:
[gong@Gong-Computer cprogram]$ gcc -g copyFile.c -o copyFile
[gong@Gong-Computer cprogram]$ ./copyFile
/*Test.c*/
#include
#include
#include
#include

/*
char * returnstring(char *string)
{
        //static char buffer[1024];
        
        char * buffer = (char *)malloc(1024);
        strcpy(buffer,string);

        return buffer;
}*/

typedef int (*array10)[10];/*array100可以作为 int a[100]的指针*/
int main()
{
        /*
        int a = 10;
        int *p = &a;

        long int  apple = 0;
        apple = sizeof(int) * p;

        printf("The Number of apple is %ld\n",apple);
        */

        int a[10];
        int i = 0;
        for(i = 0;i<10;++i)
        {
                a[i] = i;
        }

        array10 b = a;
"copydata.c" 47L, 618C       /*这说明说明复制成功了,在文件中实现了数据的复制*/    
....       

以上的代码说明了基本实现了文件的复制,后期将采用标准I/O实现文件的复制。需要注意的是Linux I/O主要是返回了完成的数据量,这个可以方便操作。文件的复制过程是一个常用的过程。但是操作的方式存在一些差别,具体问题具体分析。                                      

转载于:https://my.oschina.net/u/2408048/blog/477000

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值