/* Collection of code snippets by Arne Vajhøj */
/* (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>

#define N 5120

static char retbuf[1024];

void replace_last_line(char *fnm, char *line)
{
   FILE *fp;
   struct stat st;
   char tmpbuf[N];
   int ix,len,bufix;
   stat(fnm, &st);
   len=st.st_size<N?st.st_size:N;
   ix=st.st_size-len;
   fp=fopen(fnm,"r+b");
   fseek(fp,ix,SEEK_SET);
   fread(tmpbuf,len,1,fp);
   bufix=len-1;
   while((tmpbuf[bufix]!='\n')&&(bufix>0)) bufix--;
   ix=st.st_size-len+bufix+(bufix>0?1:0);
   fseek(fp,ix,SEEK_SET);
   fwrite(line,strlen(line),1,fp);
   fclose(fp);
   return;
}

int main(int argc,char *argv[])
{
   replace_last_line("z.txt", "ABC");
   exit(0);
}
