Overwriting in a random access file

I have a random access file opened in "r + b" mode with entries of equal length. Can I change the contents of a record after reading it and overwrite it in place?

I tried the following code, but when I start, I get: Segmentation error (dropping the kernel)

#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);
}
+3
source share
2 answers

Yes, you can. Just remember always fseekbetween reading and writing.

Submit the man page fopen:

Reading and writing can be mixed in the read / write streams in any order. Note that ANSI C requires that the file positioning function intervenes between output and input, unless the input operation encounters the end of the file.

: fopen ( perror strerror, , ).

+5

. , , , , .

+1

All Articles