Alex Purple Hosein
Alex Purple Hosein

Reputation: 43

Converting Binary File to Text File in C

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

Answers (1)

chqrlie
chqrlie

Reputation: 145297

You binary file format seems awkward:

  • you open the input file with "r": it should be opened in binary mode with "rb".
  • you first attempt to determine the file size with 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.
  • in the loop:
    • you read a single byte that you store in a part of fileLen.
    • you then read a string of 256 bytes.
    • you read a number directly, assuming the byte order and size of int is what you expect.
    • you then print the string, assuming there was a '\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

Related Questions