Linux C 两种方法实现复制拷贝文件

您所在的位置:网站首页 linux中文件复制 Linux C 两种方法实现复制拷贝文件

Linux C 两种方法实现复制拷贝文件

#Linux C 两种方法实现复制拷贝文件| 来源: 网络整理| 查看: 265

第一种方法:例如 linux 下的系统调用

#include #include #include #include #include #include #include char buff[1024]; int len; int main(int argc, char const *argv[]) { char const *src_path = argv[1]; char const *des_path = argv[2]; int fd,fd2; fd = open(src_path,O_RDWR|O_CREAT); fd2 = open(des_path,O_RDWR|O_CREAT); while(len = read(fd,buff,1024)) { write(fd2,buff,len); } return 0; } 这里主要 用到的函数是 open,read,write

其中open 函数:

第一个参数为要打开文件的路径,第二个参数是功能flag,O_RDWR表示以读写方式打开文件,O_CREAT表示如果文件不存在则创建

返回一个文件描述符,表示打开了的文件

其中 read 函数:

第一个参数是一个文件描述符,表示:从该文件描述符表示的文件读取数据

第二个参数是把从文件读到的信息放在一个缓冲数组中

第三个参数是读一次读多少字节

其中 write 函数:

第一个参数,是把数据写到哪里(写到哪个文件描述符中)

第二个参数:把缓冲数组中的数据写到文件描述符中

第三个参数:表示一次写多少字节

注意:最好向上面代码那样用一个while循环来读写数据,这样的话,read 中的第三个参数就不用设置成太大,因为他会把数据全读完才退出循环

第二种方法:用文件流

#include #include #include #include char buff[1024]; int len; int main(int argc, char const *argv[]) { FILE *in,*out; char const * src_path = argv[1]; //要被拷贝的文件路径 char const * des_path = argv[2]; //拷贝的文件放在哪里(路径) in = fopen(argv[1],"r+"); out = fopen(argv[2],"w+"); while(len = fread(buff,1,sizeof(buff),in)) { fwrite(buff,1,len,out); } return 0; } 两种方法其实有异曲同工之妙,第一种方法的文件描述符 = 第二种方法的文件流指针 in 和 out。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3