Question

I am trying to read contents of a file that is some 3KB into a buffer and then writing the contents of the buffer into another file. The file in which data is written into contains only a part of data that is written into it. Its size is around 1KB. How to write the remaining data?

fp1 = fopen("a.txt","rb");
fp2 = fopen("b.txt","wb");

fread(buffer, 1, BUFFER_SIZE,fp1);//reading from file pointed to by fp1
//BUFFER_SIZE = 3KB
fwrite(buffer, 1, BUFFER_SIZE, fp2);//writing into a file pointed to by fp2

Will a fflush after fwrite do that for me?

Was it helpful?

Solution

There is no guarantee that fread will give you all the bytes you asked for. It can give you less, which is what the return code is for.

You need to use the return code to figure out how much information to send to the fwrite.

And that checking of return codes extends to the fopen calls as well - there's no guarantees that the open will work.

By way of example, the following complete program will attempt to copy up to 3K from one file to another:

#include <stdio.h>
#include <errno.h>

int main (void) {
    FILE *fp1, *fp2;
    char buff[3*1024];
    int bytesRead;

    // Open both files.

    if ((fp1 = fopen ("a.txt", "r")) == NULL) {
        printf ("Error %d opening a.txt\n", errno);
        return 1;
    }
    if ((fp2 = fopen ("b.txt", "w")) == NULL) {
        printf ("Error %d opening b.txt\n", errno);
        fclose (fp1);
        return 1;
    }

    // Transfer only up to buffer size.

    if ((bytesRead = fread (buff, 1, sizeof (buff), fp1)) == 0) {
        // Check error case.

        if (ferror (fp1)) {
            printf ("Error reading a.txt\n");
            fclose (fp1);
            fclose (fp2);
            return 1;
        }
    }

    // Attempt transfer to destination file.

    if (fwrite (buff, 1, bytesRead, fp2) != bytesRead) {
        printf ("Error writing b.txt\n");
        fclose (fp1);
        fclose (fp2);
        return 1;
    }

    // Close all files to finish up.

    fclose (fp1);
    fclose (fp2);
    return 0;
}

OTHER TIPS

fflush(fp2) or fclose(fp2) will move the pending, buffered bytes to disk.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top