Search code examples
cfilefile-pointer

How can I keep the position of a FILE pointer in a file in another file pointer?


I have the following code in which the tmp FILE * does not keep the previous position of fp (which is 0). It actually changes along with fp when I use fseek().

Output:

fp=0 fp=40 tmp=40

How can I make it work such that tmp keeps the original position?

main()
{
        FILE *fp,*tmp;
        char *name;

        name=getfilename();

        if((fp=fopen(name,"wb"))==NULL)
        {
                puts("\n CAN'T OPEN FILE FOR SAVING...\n");
                return ;
        } 

        printf("fp=%ld",ftell(fp));

        tmp=fp;

        fseek(fp,sizeof(int)*10,SEEK_SET);

        printf("fp=%ld tmp=%ld",ftell(fp),ftell(tmp));
}

Solution

  • Both pointers point to the same FILE structure. If you wish, you can simply open the file twice, in which case, the pointers would be entirely independent.