zoukankan      html  css  js  c++  java
  • 经典范例:文件的复制

    #include<sys/types.h>
    #include<sys/stat.h>
    #include<fcntl.h>
    #include<stdio.h>
    #include<errno.h>
    #include<stdlib.h>
    #define BUFFER_SIZE 1024
    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 
    ",argv[0]);
            exit(-1);
        }
        //打开源文件
        if((from_fd=open(argv[1],O_RDONLY))==-1)
        {
            fprintf(stderr,"open %s error%s
    ",argv[1],strerror(errno));
            exit(1);
        }
        //创建目的文件
        if((to_fd=open(argv[2],O_WRONLY|O_CREAT,S_IRUSR|S_IWUSR))==-1)
        {
            fprintf(stderr,"open %s error%s
    ",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);
        exit(0);
    }
  • 相关阅读:
    OpenCV中的绘图函数
    整理不错的opencv博客
    opencv中的函数
    这是一个学习前端技术的网站
    HDU1520 Anniversary party(树形DP入门)
    CF1255C League of Leesins(图论)
    HDU4725 The Shortest Path in Nya Graph(最短路分层)
    1288C Two Arrays
    CF1294D MEX maxiszing
    CF1295C Obtain the String
  • 原文地址:https://www.cnblogs.com/leijiangtao/p/4593931.html
Copyright © 2011-2022 走看看