John Stawket
John Stawket

Reputation: 17

How to read a binary file with fread()

I'm writing a function that has to traverse through a binary file and write it to a text file. Each line of the binary file contains
l1 firstname l2 lastname ID GPA
ex) Mary Joeseph 1234 4.0

Where l1 and l2 are the lengths of first and last name, respectively, ID is an unsigned int, and GPA is a float (each 4 bytes).
How can I correctly implement a loop to traverse the binary file until it reaches EOF? Currently, the resulting text file is gibberish for the most part, how can I fix it? Any help is appreciated.

int binaryToText() //add parameters
{

unsigned char firstName[255];
unsigned char lastName[255];
unsigned int id;
float gpa;
char nLine[]= "\n";
char space[]= " ";


FILE * binfile = fopen("b2.bin", "r"); //Open and read binary file binfile
FILE * textfile = fopen("b2totxt.txt", "w");//Open and write to text file



if(NULL == binfile) //alerts and exits if binfile is not found
{
    fprintf(stderr, "Failed to open file\n");
    fflush(stderr);
    exit(1);
}


fread(&firstName, sizeof(firstName), 1, binfile);
fread(&lastName, sizeof(lastName), 1, binfile);
fread(&id, sizeof(id), 1, binfile);
fread(&gpa, sizeof(gpa), 1, binfile);

printf("%s %s %u %f", firstName, lastName, id, gpa); //test(doesnt come out right)

fprintf(textfile, "%s %s %u %1.1f\n", firstName, lastName, id, gpa);//also flawed





fclose(textfile);
fclose(binfile); //close bin file
return 0;

}

Upvotes: 0

Views: 10257

Answers (2)

autistic
autistic

Reputation: 15642

You want to read binary data, however, your file is open for reading text ("r") instead of reading binary ("rb"). Hence, fread() is possibly translating "\r\n" to "\n", which could cause issues when the underlying representation of a particular unsigned int or float value contains "\r\n" sequences.

Change this:

FILE * binfile = fopen("b2.bin", "r");

To this:

FILE * binfile = fopen("b2.bin", "rb");

In "rb", the b stands for binary mode.


However, I don't think this is your main problem, as your binary file doesn't actually contain binary representations of data; it contains human-readable representations (based on the example you gave). You should be using fscanf, not fread to read that data.

Change this:

fread(&firstName, sizeof(firstName), 1, binfile);
fread(&lastName, sizeof(lastName), 1, binfile);
fread(&id, sizeof(id), 1, binfile);
fread(&gpa, sizeof(gpa), 1, binfile);

To this:

int n = fscanf(binfile, "%s %s %u %f", firstName, lastName, &id, &gpa);

Upvotes: 4

NVS Abhilash
NVS Abhilash

Reputation: 577

FILE * binfile = fopen("b2.bin", "r");

This should be

FILE * binfile = fopen("b2.bin", "rb"); To open any binary files.

Upvotes: 0

Related Questions