Tried and true simple file copying code in C?

前端 未结 7 1154
醉梦人生
醉梦人生 2020-12-03 09:09

This looks like a simple question, but I didn\'t find anything similar here.

Since there is no file copy function in C, we have to implement file copying ourselves,

相关标签:
7条回答
  • 2020-12-03 09:32

    This is the function I use when I need to copy from one file to another - with test harness:

    /*
    @(#)File:           $RCSfile: fcopy.c,v $
    @(#)Version:        $Revision: 1.11 $
    @(#)Last changed:   $Date: 2008/02/11 07:28:06 $
    @(#)Purpose:        Copy the rest of file1 to file2
    @(#)Author:         J Leffler
    @(#)Modified:       1991,1997,2000,2003,2005,2008
    */
    
    /*TABSTOP=4*/
    
    #include "jlss.h"
    #include "stderr.h"
    
    #ifndef lint
    /* Prevent over-aggressive optimizers from eliminating ID string */
    const char jlss_id_fcopy_c[] = "@(#)$Id: fcopy.c,v 1.11 2008/02/11 07:28:06 jleffler Exp $";
    #endif /* lint */
    
    void fcopy(FILE *f1, FILE *f2)
    {
        char            buffer[BUFSIZ];
        size_t          n;
    
        while ((n = fread(buffer, sizeof(char), sizeof(buffer), f1)) > 0)
        {
            if (fwrite(buffer, sizeof(char), n, f2) != n)
                err_syserr("write failed\n");
        }
    }
    
    #ifdef TEST
    
    int main(int argc, char **argv)
    {
        FILE *fp1;
        FILE *fp2;
    
        err_setarg0(argv[0]);
        if (argc != 3)
            err_usage("from to");
        if ((fp1 = fopen(argv[1], "rb")) == 0)
            err_syserr("cannot open file %s for reading\n", argv[1]);
        if ((fp2 = fopen(argv[2], "wb")) == 0)
            err_syserr("cannot open file %s for writing\n", argv[2]);
        fcopy(fp1, fp2);
        return(0);
    }
    
    #endif /* TEST */
    

    Clearly, this version uses file pointers from standard I/O and not file descriptors, but it is reasonably efficient and about as portable as it can be.


    Well, except the error function - that's peculiar to me. As long as you handle errors cleanly, you should be OK. The "jlss.h" header declares fcopy(); the "stderr.h" header declares err_syserr() amongst many other similar error reporting functions. A simple version of the function follows - the real one adds the program name and does some other stuff.

    #include "stderr.h"
    #include <stdarg.h>
    #include <stdlib.h>
    #include <string.h>
    #include <errno.h>
    
    void err_syserr(const char *fmt, ...)
    {
        int errnum = errno;
        va_list args;
        va_start(args, fmt);
        vfprintf(stderr, fmt, args);
        va_end(args);
        if (errnum != 0)
            fprintf(stderr, "(%d: %s)\n", errnum, strerror(errnum));
        exit(1);
    }
    

    The code above may be treated as having a modern BSD license or GPL v3 at your choice.

    0 讨论(0)
提交回复
热议问题