Retrieve user specified lines from a text & store these lines to another destination file

#include <stdio.h>
 #include <process.h>
 
 #define MAX 500
 void makendx(FILE *rfp, FILE *nfp)
 {
    long line=0, spot=0;
    int ch;
 
    /* leave space for storing total number of lines in file*/
    fseek(nfp,(long)sizeof(long),0);
 
    /* Write the position of the first line*/
    fwrite((char*)&spot, sizeof(long),1,nfp);
 
    /* loop to store the positions of the subsequent lines */
    while((ch=fgetc(rfp))!= EOF){
           ++spot;
           if(ch=='n'){
                  ++spot;
                  line++;
                  fwrite((char*)&spot,sizeof(long),1,nfp);
           }
    }
 
    /* Go to the top of the index file and store total lines*/
    rewind(nfp);
    fwrite((char*)&line,sizeof(long),1,nfp);
    fclose(nfp);
    return;
 }
 
 void makeout(FILE *rfp, FILE *wfp, FILE *nfp)
    {
    long lines,lineno,start,end;
    char chunk[MAX];
 
    /*reopen index  for reading*/
    if((nfp=fopen("tmp.ndx","rb+"))==NULL){
           fprintf(stderr,"Cannot open tmp.ndxn");
           exit(5);
    }
 
    /* read total numbers of lines in source*/
    fread((char*)&lines,sizeof(long),1,nfp);
 
    printf("Enter line numbers to retrieve one by one:n");
 
    /* loop to get desired line and store to destination*/
    while(1){
           scanf("%ld",&lineno);
           if(lineno==0)
                  return;
 
           if(lineno>lines)
                  continue;
 
           /* set file position indicator to get starting position*/
           fseek(nfp,lineno*sizeof(long),0);
 
           /* read starting position*/
           fread((char*)&start,sizeof(long),1,nfp);
 
           /* read starting position of next line to count number of
           characters in the current one*/
           fread((char*)&end,sizeof(long),1,nfp);
 
           /* position the indicator to the start of source*/
           fseek(rfp,start,0);
           /*read desired number of character*/
           fread((char*)&chunk,1,end-start-1,rfp);
 
           /* write the line to destination file*/
           fwrite((char*)&chunk,1,end-start-1,wfp);
 
    }
    return;
 }
 
 int main(int argc, char *argv[])
    {
    FILE *rfp, *wfp, *nfp;
    if(argc!=3){
           fprintf(stderr,"Usage : %s <source> <destination>n",argv[0]);
           exit(1);
    }
    if((rfp=fopen(*++argv,"r"))== NULL){
           fprintf(stderr,"Cannot open %s n",*argv);
           exit(2);
    }
    if((wfp=fopen(*++argv,"w"))==NULL){
           fprintf(stderr,"Cannot open %sn", *argv);
           exit(3);
    }
    if((nfp=fopen("tmp.ndx","wb+"))==NULL){
           fprintf(stderr,"Cannot open tmp.ndxn");
           exit(4);
    }
    makendx(rfp,nfp);
    makeout(rfp,wfp,nfp);
    fclose(rfp);
    fclose(wfp);
    fclose(nfp);
    return 0;
 }

Enjoyed this post? Share it!

 

Leave a comment

Your email address will not be published.