Search code examples
cbinaryfwritefread

How do I read back an 8 byte number after writing it to a file?


I am able to write an 8 byte representation of a number to a file. However when I go to read it back, I do not get the number I am expecting. In my code below, I am attempting to write and read back the number 5000 to testfile.txt.

#include <stdio.h>

int main()
{
    // Open file
    FILE *fp;
    if ((fp = fopen("testfile.txt","w+")) == NULL) 
    {
        // Handle error
    }

    // Write 8 byte number to file
    long long n = 5000;
    fwrite(&n, 8, 1, fp);

    // Seek to EOF and check that the file is 8 bytes
    fseek(fp, 0, SEEK_END);
    long locend = ftell(fp);
    printf("Endbyte: %ld\n",locend);

    // Seek back to start of file and print out location
    fseek(fp, -8, SEEK_END);
    long loc = ftell(fp);
    printf("Location: %ld\n",loc);

    // Read and print out number
    long long *out;
    fread(out, 8, 1, fp);
    long long num = (long long) out;
    printf("Number: %lld\n", num); 

    /* Cleanup */
    close(fp); 
    return(0);
}

Doing a hexdump of testfile.txt gives me the following:

00000000  88 13 00 00 00 00 00 00                   |........|                 
00000008

The binary representation of the hex values of 13 and 88 make 5000, which confirms that it is being written correctly (I believe).

Unfortunately the output of my program does not agree:

Endbyte: 8                                                                    
Location: 0                                                             
Number: 140734934060848

As you can see, the number read back does not match the number written. I am assuming it is a problem with the way I am reading it back.


Solution

  • I'm surprised that's even running without crashing! fread is essentially the exact same thing as fwrite, just in the other direction. It expects a pointer to a block of memory, but you're passing it an uninitialized pointer.

    long long *out; //This is a pointer that is pointing to an undefined area of memory.
    fread(out, 8, 1, fp); //fread is now writing the number to that undefined area of memory
    

    What you want to do is create a plain old long long and pass a reference to it just like you did with fwrite.

    long long out; //This is a location in memory that will hold the value
    fread(&out, 8, 1, fp); //fread is now writing the number to the area of memory defined by the 'out' variable