Chris
Chris

Reputation: 8412

fwrite keeps failing not sure why

In my code below, the file is being written correctly as far as I can tell. When I look in the file floats.dat I see this stream of binary ÍÌL@33c@ÍÌÜ@ffFAßOeA^@^@bBf6zE33äCff<83>BÍ̦B

However my program always ends up triggering this if statement:

if(fread(inputFloats, sizeof(float), LENGTH, binaryFile) < LENGTH)
{
   fprintf(stderr, "Problem reading some or all data from %s\n\n", binaryFileName);
   return EXIT_FAILURE;
}

Does anybody see something I've done wrong here? Full code below.

#include <stdlib.h>
#include <stdio.h>
#define LENGTH 10

int main(void)
{
   FILE *binaryFile, *textFile;
   char *binaryFileName = "floats.dat", *textFileName = "floats.txt";
   float floats[LENGTH] = {3.2, 3.55, 6.9, 12.4, 14.332, 56.5, 4003.4, 456.4, 65.7, 83.4};
   float inputFloats[LENGTH];
   int i;

   if((binaryFile = fopen(binaryFileName, "r+")) == NULL)
   {
      fprintf(stderr, "Problem opening %s", binaryFileName);
   }

   if(fwrite(floats, sizeof(float), LENGTH, binaryFile) < LENGTH)
   {
      fprintf(stderr, "Problem writing some or all data to %s\n", binaryFileName);
      return EXIT_FAILURE;
   }

   printf("DATA WRITTEN SUCCESSFULLY\n");

   if(fread(inputFloats, sizeof(float), LENGTH, binaryFile) < LENGTH)
   {
      fprintf(stderr, "Problem reading some or all data from %s\n\n", binaryFileName);
      return EXIT_FAILURE;
   }

   for(i = 0; i < LENGTH; i++)
   {
      printf("float[%d] = %f\n", i, floats[i]);
   }

   return EXIT_SUCCESS;
}

Upvotes: 0

Views: 2391

Answers (4)

Erik
Erik

Reputation: 91260

  • You're not working with text data so you should specify a binary mode when opening the file. Use r+b instead of r+
  • You need to fseek(binaryFile, 0, SEEK_SET) to "rewind" the file after writing. rewind can also be used for this case - fseek allows you to position the read/write pointer wherever you want.

Upvotes: 7

steabert
steabert

Reputation: 6878

You forgot to rewind your file before reading it:

rewind(binaryFile);

Upvotes: 1

Giovanni Funchal
Giovanni Funchal

Reputation: 9170

When you finish writing to the file, the FILE pointer is at the end of it, so of course if you try reading it will not work. Try using fseek to move the pointer to the beginning of the file before reading.

Please avoid this :

if((binaryFile = fopen(binaryFileName, "r+")) == NULL) {

and prefer this:

binaryFile = fopen(binaryFileName, "rb+");
if(!binaryFile) {

Upvotes: 0

Chowlett
Chowlett

Reputation: 46667

The FILE structure keeps a record of where in the file it is currently pointing. Since you've just written to binaryFile, the file pointer is at the end of what you've written.

You therefore need to rewind the file, using fseek(binaryFile, 0, SEEK_SET); before you read.

Upvotes: 1

Related Questions