国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

Linux下C語言實現文件拷貝--轉

2019-11-09 18:53:54
字體:
來源:轉載
供稿:網友

linux下C語言實現文件拷貝

/*

   Function:copy file from file1 to file2

   How to execute: ./copyfile file1 file2   (under Linux)

   Data:2007-05-09

*/

 

#include <stdio.h>      /*fPRintf(),stderr,BUFSIZ*/

#include <stdlib.h>     /**/

#include <string.h>     /*stderror()*/

#include <fcntl.h>      /*open(),flag*/

#include <errno.h>      /*errno*/

#include <unistd.h>     /*ssize_t*/

#include <sys/types.h>

#include <sys/stat.h>   /*mode_t*/

 

#define BUFFER_SIZE 3

 

int main(int argc,char **argv)

{

   int from_fd,to_fd;

   int bytes_read,bytes_write;

   char buffer[BUFFER_SIZE];

   char *ptr;

 

   if(argc!=3)

   {

     fprintf(stderr,"Usage:%s fromfile tofile/n/a",argv[0]);

     exit(1);

   }

 

   /* 打開源文件 */

   if((from_fd=open(argv[1],O_RDONLY))==-1)   /*open file readonly,返回-1表示出錯,否則返回文件描述符*/

   {

     fprintf(stderr,"Open %s Error:%s/n",argv[1],strerror(errno));

     exit(1);

   }

 

   /* 創建目的文件 */

   /* 使用了O_CREAT選項-創建文件,open()函數需要第3個參數,

      mode=S_IRUSR|S_IWUSR表示S_IRUSR 用戶可以讀 S_IWUSR 用戶可以寫*/

   if((to_fd=open(argv[2],O_WRONLY|O_CREAT,S_IRUSR|S_IWUSR))==-1) 

   {

     fprintf(stderr,"Open %s Error:%s/n",argv[2],strerror(errno));

     exit(1);

   }

 

   /* 以下代碼是一個經典的拷貝文件的代碼 */

   while(bytes_read=read(from_fd,buffer,BUFFER_SIZE))

   {

     /* 一個致命的錯誤發生了 */

     if((bytes_read==-1)&&(errno!=EINTR)) 

         break;

     else if(bytes_read>0)

     {

       ptr=buffer;

       while(bytes_write=write(to_fd,ptr,bytes_read))

       {

         /* 一個致命錯誤發生了 */

         if((bytes_write==-1)&&(errno!=EINTR))

             break;

         /* 寫完了所有讀的字節 */

         else if(bytes_write==bytes_read) 

             break;

         /* 只寫了一部分,繼續寫 */

         else if(bytes_write>0)

         {

           ptr+=bytes_write;

           bytes_read-=bytes_write;

         }

       }

       /* 寫的時候發生的致命錯誤 */

       if(bytes_write==-1)

           break;

     }

   }

   close(from_fd);

   close(to_fd);

   return;


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 芜湖市| 页游| 关岭| 湟中县| 平谷区| 常州市| 泌阳县| 南通市| 临夏县| 延边| 铜鼓县| 布拖县| 阿勒泰市| 巴彦县| 龙州县| 宁津县| 岳普湖县| 南雄市| 蓝山县| 长春市| 晴隆县| 若尔盖县| 祁阳县| 景洪市| 灵石县| 原阳县| 丹凤县| 周口市| 馆陶县| 中方县| 全州县| 松潘县| 镇沅| 牙克石市| 望城县| 黎川县| 高尔夫| 抚顺市| 普宁市| 班玛县| 双辽市|