Linux C编程之IO-文件拷贝

Linux C编程:IO


1.1文件拷贝

本次文件拷贝需要使用到如下三个函数原型:
打开文件
FILE * fopen(const char * path,const char * mode);
相关函数:open,fclose,fopen_s,_wfopen
返回值:文件顺利打开后,指向该流的文件指针就会被返回。如果文件打开失败则返回NULL,并把错误代码存在errno 中。
读、写文件
#include 
 size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
 size_t fwrite(const void *ptr, size_t size, size_t nmemb,
                     FILE *stream);

返回值
On success, fread() and fwrite() return the number of items read or written. This number equals the number of bytes transferred only when size is 1. If an error occurs, or the end of the file is reached, the return value is a short item count (or zero).fread() does not distinguish between end-of-file and error, and callers must use feof(3) and ferror(3) to determine which occurred.**

实现代码

//
// Created by 挽秋 on 3/23/17.
//
/*function : copy file from file1 to file2*/
#include             /*fprinf(), stderr, BUFSIZE*/
#include 
#include          //stderror()
#include           //open(), flag
#include           //errno
#include          //ssize_t
#include 
#include        //mode_t

#define BUFFER_SIZE 3
int main(int argc, char **argv)
{
    int inputFD, targetFD;
    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( (inputFD = open(argv[1], O_RDONLY)) == -1)
    {
        //open file readonly,返回-1表示出错,否则返回文件描述符
        fprintf(stderr, "Open %s Error: %s\n", argv[1], strerror(errno));
        exit(1);
    }
    //创建目的文件
    // 使用了O_CREATE选项创建文件,open()函数需要第三个参数
    //mode = S_IRUSER|S_IWUSER表示S_ISUSR用户可以读S_IWUSR用户可以写
     if( (targetFD = 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(inputFD, buffer, BUFFER_SIZE))
    {
        //文件读取发生错误
        if( (bytes_read == -1)&& (errno != EINTR))
            break;
        else if(bytes_read > 0)
        {
            ptr = buffer;
            while(bytes_write = write(targetFD, ptr, bytes_read))
            {
                //写内容发生错误
                if( (bytes_write == -1) && errno != EINTR) break;
                else if(bytes_write > 0)
                {
                    ptr += bytes_write;
                    bytes_read -= bytes_write;
                }
                else if(bytes_read == bytes_write) break;
            }
            //写文件发生错误
            if(bytes_write == -1)
                break;
        }
    }
    close(inputFD);
    close(targetFD);
    return 1;
}

你可能感兴趣的:(linux,c/c++)