Q:

Overwriting in a random access file

I have a random access file opened in "r+b" mode with records of equal length. Can I change the contents of a record after reading it and overwrite in place?
I tried the following code but on running I get: Segmentation fault(core dumped)
#include<stdio.h>

int main()
{
   struct tala {
      int rec_no;
      long file_no;
   };
   FILE *file_locking;
   struct tala t,f;
   file_locking = fopen("/path/to/my/file.bin", "rb+");
   t.rec_no = 1;
   t.file_no = 3;
   if (fwrite(&t, sizeof(struct tala),1,file_locking)==0)
      printf("Error opening file");
   t.rec_no=0;
   rewind(file_locking);
   if (fwrite(&t, sizeof(struct tala),1,file_locking)==0)
      printf("Error opening file");
   rewind(file_locking);
   if (fread(&f, sizeof(struct tala),1,file_locking)==0)
      printf("Error opening file");
   printf("\n %d",f.rec_no);
   printf("\n %ld", f.file_no);
   fclose(file_locking);
}

A:

Yes you can. Just remember to always fseek between reads and writes.
Quote the fopen man page:

Reads and writes may be intermixed on read/write streams in any order.  Note that ANSI C requires that a file positioning function intervene between output and input, unless an input operation encounters end-of-file.

Extra tip: always check the return value of fopen and related functions, and handle errors (use perror or strerror to print out what failed).

