Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read a binary file in c? (video, images, or text)

Tags:

c

fread

I am trying to copy a file from a specified library to the current directory. I can copy text files perfectly. Any other files become corrupt. The program detects a feof before it should.

#include <stdio.h>

int BUFFER_SIZE = 1024;
FILE *source;
FILE *destination;
int n;
int count = 0;
int written = 0;

int main() {
    unsigned char buffer[BUFFER_SIZE];

    source = fopen("./library/rfc1350.txt", "r");

    if (source) {
        destination = fopen("rfc1350.txt", "w");

        while (!feof(source)) {
            n = fread(buffer, 1, BUFFER_SIZE, source);
            count += n;
            printf("n = %d\n", n);
            fwrite(buffer, 1, n, destination);
        }
        printf("%d bytes read from library.\n", count);
    } else {
        printf("fail\n");
    }

    fclose(source);
    fclose(destination);

    return 0;
}
like image 862
Collin Price Avatar asked Feb 21 '10 19:02

Collin Price


People also ask

How do you open a binary file in text?

To open the Binary Editor on an existing file, go to menu File > Open > File, select the file you want to edit, then select the drop arrow next to the Open button, and choose Open With > Binary Editor.

Can we read a binary file using a text editor?

Since the file is not encoded as text, it can not be read by the text editor. This article takes a look at what binary files are, how they are different from traditional text files, and where to use them.


1 Answers

Are you on a Windows machine? Try adding "b" to the mode strings in the calls to fopen.

From man fopen(3):

The mode string can also include the letter 'b' either as a last character or as a character between the characters in any of the two-character strings described above. This is strictly for compatibility with C89 and has no effect; the 'b' is ignored on all POSIX conforming systems, including Linux. (Other systems may treat text files and binary files differently, and adding the 'b' may be a good idea if you do I/O to a binary file and expect that your program may be ported to non-Unix environments.)
like image 126
Hans W Avatar answered Sep 25 '22 04:09

Hans W