/* Collection of code snippets by Arne Vajhøj */
/* (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) */
#include <stdio.h>
#include <string.h>

#define RECSIZ 4
#define FNM "cx.fix"

static long recno(int ix)
{
   return (ix - 1) * RECSIZ;
}

static int eof = 0;
static char ZERO[RECSIZ] = { 0 };

void test_write_one(FILE *fp, int ix, char *buf)
{
   if(ix > eof) // has to zero out previous records never written before
   {
      fseek(fp, recno(eof + 1), SEEK_SET);
      for(int i = eof + 1; i < ix; i++)
      {
         fwrite(ZERO, RECSIZ, 1, fp);
      }
      eof = ix;
   }
   fseek(fp, recno(ix), SEEK_SET);
   fwrite(buf, RECSIZ, 1, fp);
}

void test_write()
{
   char mrs[11];
   sprintf(mrs, "mrs=%d", RECSIZ);
   FILE *fp = fopen(FNM, "wb", "rfm=fix", mrs, "rat=cr");
   test_write_one(fp, 3, "CCCC");
   test_write_one(fp, 2, "BBBB");
   test_write_one(fp, 1, "AAAA");
   fclose(fp);
}

void test_read_sequential()
{
   FILE *fp = fopen(FNM, "rb");
   char buf[RECSIZ+1];
   while(fread(buf, RECSIZ, 1, fp))
   {
      buf[RECSIZ] = 0;
      printf("|%s| %d\n", buf, strlen(buf));
   }
   fclose(fp);
}

void test_read_random_one(FILE *fp, int ix)
{
   fseek(fp, recno(ix), SEEK_SET);
   char buf[RECSIZ+1];
   fread(buf, RECSIZ, 1, fp);
   buf[RECSIZ] = 0;
   printf("|%s| %d\n", buf, strlen(buf));
}

void test_read_random()
{
   FILE *fp = fopen(FNM, "rb");
   test_read_random_one(fp, 3);
   test_read_random_one(fp, 2);
   test_read_random_one(fp, 1);
   fclose(fp);
}

int main(int argc, char *argv[])
{
   printf("C seek\n");
   test_write();
   test_read_sequential();
   test_read_random();
   return 0;
}
