How do I copy files?

Untitled Forums Assignment Help How do I copy files?

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #1264
    Aakanksha
    Participant

    How do I copy files?

    #9826
    Aakanksha
    Participant

    Either use system() to invoke your operating system’s copy utility, or open the source and destination files (using fopen or some lower-level file-opening system call), read characters or blocks of characters from the source file, and write them to the destination file. Here is a simple example:

    #include <stdio.h>

    int copyfile(char *fromfile, char *tofile)

    {

    FILE *ifp, *ofp;

    int c;

    if((ifp = fopen(fromfile, “r”)) == NULL) return -1;

    if((ofp = fopen(tofile, “w”)) == NULL) { fclose(ifp); return -1; }

    while((c = getc(ifp)) != EOF)

    putc(c, ofp);

    fclose(ifp);

    fclose(ofp);

    return 0;

    }

    To copy a block at a time, rewrite the inner loop as

    while((r = fread(buf, 1, sizeof(buf), ifp))> 0)

    fwrite(buf, 1, r, ofp);

    where r is an int and buf is a suitably-sized array of char.

Viewing 2 posts - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.