Reputation: 43
I'm having an issue trying to convert a Binary File into a text file. Right now, I'm getting an output of "hello 16". I should be getting 5 lines of output, in which the first line should be "hello 32". I'm unsure where I went wrong, but I've been trying to figure it out for a few hours now. Link to Binary File
void BinaryToText(char *inputFile, char *outputFile) {
unsigned char str[256];
unsigned int num;
int fileLen;
FILE *finp;
FILE *fout;
finp = fopen(inputFile, "r");
fout = fopen(outputFile, "w");
fseek(finp, 0, SEEK_END);
fileLen = ftell(finp);
fseek(finp, 0, SEEK_SET);
while (fread(&fileLen, sizeof(char), 1, finp) == 1) {
fread(&str, sizeof(str), 1, finp);
fread(&num, sizeof(int), 1, finp);
fprintf(fout, "%s %d\n", str, num);
}
fclose(finp);
fclose(fout);
}
Upvotes: 2
Views: 16017
Reputation: 145297
You binary file format seems awkward:
"r"
: it should be opened in binary mode with "rb"
.ftell()
. Be aware that this will not work for pipes and devices. In you case it would not matter as you do not use fileLen
anyway. fileLen
.int
is what you expect.'\0'
in the file, otherwise you would invoke undefined behavior.It is hard to tell what is wrong without seeing the writing code.
Note that the binary file should be open with "rb"
to prevent spurious conversion of linefeed sequences on some platforms, notably Windows.
EDIT:
Form the extra information provided in the comments, here is a modified version that should parse you binary file more appropriately:
void BinaryToText(char *inputFile, char *outputFile) {
unsigned char str[256];
unsigned int num; // assuming 32 bit ints
int i, len;
FILE *finp = fopen(inputFile, "rb");
FILE *fout = fopen(outputFile, "w");
while ((len = fgetc(finp)) != EOF) {
fread(str, len, 1, finp);
str[len] = '\0';
num = (unsigned int)fgetc(finp) << 24;
num |= fgetc(finp) << 16;
num |= fgetc(finp) << 8;
num |= fgetc(finp);
fprintf(fout, "%s %d\n", (char*)str, num);
}
fclose(finp);
fclose(fout);
}
Upvotes: 1