CITS2002 Systems Programming  
prev
next CITS2002 CITS2002 schedule  

Reading and writing files of binary data, continued

However, when managing files of arbitrary data, possibly including null-bytes as well, we must use different functions to handle binary data:


#include <stdio.h>
#include <stdlib.h>

void copyfile(char destination[], char source[])
{
    FILE        *fp_in   = fopen(source, "rb");
    FILE        *fp_out  = fopen(destination,  "wb");

//  ENSURE THAT OPENING BOTH FILES HAS BEEN SUCCESSFUL
    if(fp_in != NULL && fp_out != NULL) {

        char    buffer[BUFSIZ];
        size_t  got, wrote;

        while( (got = fread(buffer, 1, sizeof buffer, fp_in)) > 0) {  
            wrote = fwrite(buffer, 1, got, fp_out);
            if(wrote != got) {
                printf("error copying files\n");
                exit(EXIT_FAILURE);
            }
        }

    }

//  ENSURE THAT WE ONLY CLOSE FILES THAT ARE OPEN
    if(fp_in != NULL) {
        fclose(fp_in);
    }
    if(fp_out != NULL) {
        fclose(fp_out);
    }
}

NOTE - The access mode flag "b" has been used in both calls to fopen() as we're anticipating opening binary files. This flag has effect only on Windows systems, and is ignored on Linux and macOS. This flag has no effect when reading and writing text files.

While we might request that fread() fetches a known number of bytes, fread() might not provide them all!

  • we might be reading the last "part" of a file, or
  • the data may be arriving (slowly) over a network connection, or
  • the operating system may be too busy to provide them all right now.

 


CITS2002 Systems Programming, Lecture 7, p13, 12th August 2024.