I have been struggling with this little bit of my code for a very long time now and I need some help. I tried a lot to figure this out, but my output always differed from what I expected. I am trying to convert a binary file that has multiple lines into a text file. The problem has to do with my while loop because removing the while loop and running the code with a file that has only one line works perfectly. My code is as follows:
void binaryToText(char *inputFile, char *outputFile){
int sID;
float gpa;
char firstName[256], lastName[256];
unsigned char firstNameLen, lastNameLen;
FILE *finp = fopen(inputFile, "rb");
FILE *fout = fopen(outputFile, "w");
if((finp != NULL)&&(fout != NULL)){
while(!feof(finp)){
fread(&firstNameLen, 1, 1, finp);
fread(firstName, firstNameLen, 1, finp);
firstName[firstNameLen] = '\0';
fread(&lastNameLen, 1, 1, finp);
fread(lastName, lastNameLen, 1, finp);
lastName[lastNameLen] = '\0';
fread(&sID, 4, 1, finp);
fread(&gpa, 4, 1, finp);
fprintf(fout, "%s %s %d %1.1f\n", firstName, lastName, sID, gpa);
}
}
fclose(finp);
fclose(fout);
}
My output is supposed to look like:
mary smith 1 3.9
george washington 2 4.0
james bond 7 3.2
My output with feof
is:
mary smith 1 3.9
george washington 2 4.0
james bond 7 3.2
james bond 7 3.2
I tried using fread
in the form 'while (nmemb == (nret = fread(str, sizeof *str, nmemb, finp))) != NULL`, but my output was still wrong. Please how can I correctly make a loop that gives me the desired output?