2

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));
}
Dan Fego
  • 13,644
  • 6
  • 48
  • 59
MattSt
  • 1,024
  • 2
  • 16
  • 35
  • 3
    Both `tmp` and `fp` point to the same thing, so any modification to one pointer will "affect" the other. If I understand your question correctly, you basically want 2 different read/write positions within the same file stream, correct? – Drew McGowen Jul 17 '14 at 15:11
  • yes..correct.How can this be done? – MattSt Jul 17 '14 at 15:12
  • 2
    @matts what about just using `ftell` to get the position and `fseek` to restore it? – Maciej Piechotka Jul 17 '14 at 15:13
  • AFAIK this is not "natively" supported, I imagine due to some sort of race condition and/or ambiguity. I think one alternative is to manually save and restore the position as you need it? – Drew McGowen Jul 17 '14 at 15:14
  • 3
    Depending on the system (ie not windows): `tmp = fopen(name, "rb"); fseek(tmp, ftell(fp), SEEK_SET);` But be _very, very, very_ careful – Elias Van Ootegem Jul 17 '14 at 15:15
  • Please see the below link - – rohit Jul 17 '14 at 15:20
  • 1
    If supported (ie linux), you could open the file using `open` with `O_SYNC` flag, to ensure the fd blocks the process – Elias Van Ootegem Jul 17 '14 at 15:27

1 Answers1

2

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.

qdot
  • 6,195
  • 5
  • 44
  • 95