Tuesday 5 April 2022

Reverse the contents of a file and store in another file using fseek in c

 #include <stdio.h>

#include<stdlib.h>

int main()

{

    FILE *fp1,*fp2;

    fp1=fopen("input.txt","r");

    fp2=fopen("output.txt","w");

    char ch;

    fseek(fp1,-1,SEEK_END);

    while(1)

    {

        ch=fgetc(fp1);

        fputc(ch,fp2);

        if(fseek(fp1,-2,SEEK_CUR) <0) 

        break;

    }

    fclose(fp1);

    fclose(fp2);

    return 0;

}

======(OR) =====

#include <stdio.h>

#include<stdlib.h>

int main()

{

    FILE *fp1,*fp2;

    fp1=fopen("input.txt","r");

    fp2=fopen("output.txt","w");

    char ch;

    int c,i=1;

    fseek(fp1,0,SEEK_END);

    for(c=ftell(fp1);i<=c;i++)

    {

        fseek(fp1,-i,SEEK_END);

        ch=fgetc(fp1);

        fputc(ch,fp2);

    }

    fclose(fp1);

    fclose(fp2);

    return 0;

}


No comments:

Post a Comment