0
votes

This is a function that use a set of predefined code to encode input file (infp) to output file (outfp) (in normal text mode)

void encode( char *codes[], FILE *infp, FILE *outfp) {
    while (infp) {
        if (feof(infp)) {
            break;
        }
        char buffer[256];
        sprintf(buffer, "%s", codes[fgetc(infp)]);
        printf("%lu, %s\n", strlen(buffer), buffer); //this works
        fwrite(buffer, sizeof(char), strlen(buffer), outfp);
    }
};

codes is an array of char array with size 256
for example codes[65] returns the code of ascii char A
but then the length of code is different for each ascii char, and the max is 256

the printf line works perfectly fine, I got something like for example:

6, 100110
5, 00000
4, 0010
3, 110
5, 01011
4, 0001

so I expect the output text file will be 100110000000010110010110001
but I got nothing for the fwrite line, i.e. the output text file is blank,
not until I put the 3rd argument into 256, i.e.

fwrite(buffer, sizeof(char), 256, outfp);

but the output sticks with a lot of null and weird characters enter image description here

Please help. Thank you in advance!

1

1 Answers

1
votes

See definition of feof() [feof() reference][1] [1]: https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/feof

"For example, if a file contains 10 bytes and you read 10 bytes from the file, feof will return 0 because, even though the file pointer is at the end of the file, you have not attempted to read beyond the end. Only after you try to read an 11th byte will feof return a nonzero value."

while doesn't stop (it's useless condition, by the way), and feof() doesn't return 1 until it's too late, you get -1 from fgetc(), and use this as index in array, probably get exception, and program crashes before closing output file.

if (!infp || !outfp) {
    // Check that files opened successfully
    return;
}

while (true) {
    int index = fgetc(infp);
    if (index < 0) {
        // fgetc() return -1 on end of file
        break;
    }
    char buffer[256];
    sprintf(buffer, "%s", codes[index]);
    printf("%lu, %s\n", strlen(buffer), buffer); //this works
    fwrite(buffer, sizeof(char), strlen(buffer), outfp);
}
...
// Output file must be closed, otherwise it will be empty
fclose(outfp);