You are here:

C/fwrite and fread functions in C

Advertisement


Question
I wrote the following code but when I print it on the screen, it does not shows the int 123. I am suppose to write the int to a wav file but I am just testing it out on a text file. Where did it went wrong and what will be different for wav file? Thank you very much.


int f(const char *file_name)
{
   FILE *fp;
   unsigned int a[1] = {123}, b;
   fp = fopen(file_name, "wb");
   fwrite(a, 1, 4, fp);
   fseek(fp, 0, SEEK_SET);
   fread(&b, 1, 4, fp);
   printf("%u", b);
   fclose(fp);
}

int main()
{
   char *i = "tested.txt";
   f(i);
}

Answer
Hello Pearson.

The fread is failing because the file is opened only for writing. You need to open it for reading and writing. This can be done with "rb+" but that will fail if the file does not exist. It can be done with "wb+". That will create the file if it does not exist, but it will also erase the contents of an existing file. You probably want the function to fail if the wav doesn't exist, so "rb+" is probably what you want. In the sample code below, I handle both cases. I've included the sample code to show you error checking. The error checking actually helped me to figure out where the problem was.

#include <stdio.h>
#include <errno.h>

int f(const char *file_name)
{
  FILE *fp;

  /* Notice how this constant is used to keep things consistent in the program */
#  define COUNT 3
  unsigned int a[COUNT] = {123, 456, 789};
  unsigned int b;

  /* first try to open an existing file.
  If the file does not exist this will fail.
  In that case, open using wb+. The wb+ mode would destroy
  an existing file so that is why we attempt to open with
  rb+ first.
  */
  fp = fopen(file_name, "rb+");
  if (fp == NULL) fp = fopen(file_name, "wb+");
  if (fp == NULL)
  {
      printf("Open error: %s\n", strerror(errno));
      return -1;
  }

  /*
  The fwrite returns the count of the number of items written
  Here we are saying that each item the same size as an
  unsigned int.
  */
  if (fwrite(a, sizeof(unsigned int), COUNT, fp) != COUNT)
  {
      printf("Write error: %s\n", strerror(errno));
  }

  if (fseek(fp, 0, SEEK_SET) != 0)
  {
      printf("Seek error: %s\n", strerror(errno));
  }

  if ((readCount = fread(&b, sizeof(unsigned int), 1, fp)) != 1)
  {
      printf("Read error: %s\n", strerror(errno));
  }
  else
  {
      printf("%u", b);
  }

  fclose(fp);

  return 0;
}

int main()
{
  char *i = "tested.txt";
  f(i);
}

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Zlatko

Expertise

No longer taking questions.

Experience

No longer taking questions.

Education/Credentials
No longer taking questions.

©2012 About.com, a part of The New York Times Company. All rights reserved.