12

I have a file opened with fopen. There is a way to reopen the same file (while it is opened) but have a different seek? (so i can use fread independently)

polslinux
  • 1,739
  • 9
  • 34
  • 73
  • Yes, but why didn't you just try it? (Might actually be OS dependent.) – Georg Schölly Mar 25 '13 at 17:08
  • 1
    If you want multiple offsets within the file to read, `mmap()` may be an option too, depending on your OS. Then you can just index into the file using memory addresses. – FatalError Mar 25 '13 at 17:11
  • 4
    @GeorgSchölly that is often a very bad recommendation in languages with undefined/unspecified/implementation defined behaviour. – BoBTFish Mar 25 '13 at 17:12
  • 1
    @BoBTFish: You're right. Didn't think of that at all. Thanks for the helpful hint. :) – Georg Schölly Mar 25 '13 at 17:16

1 Answers1

7

there is no problem if you keep reading only.

Be careful if you write in the file especially if you have 2 threads that access with read/write to the file at the same time

If your code looks like that

FILE *fp1, *fp2;

fp1 = fopen("file", "r");
fp2 = fopen("file", "r");

then you have 2 seeks in the same file. and the position of seeks are independent. reading from fp1 does not have any impact in fp2

MOHAMED
  • 41,599
  • 58
  • 163
  • 268
  • 1
    @polslinux the other option (and probably more stable one) is to create a structure that maintains each seek point, and use a function to read from either head. – Richard J. Ross III Mar 25 '13 at 17:10
  • so there is no problem. you can open the file many times and have many seeks at the same time – MOHAMED Mar 25 '13 at 17:11
  • open the file with a new file descriptor otherwise you will loose the seek of the last file descriptor – MOHAMED Mar 25 '13 at 17:12
  • 1
    Careful, it is implementation-defined, see: https://stackoverflow.com/a/50114472/9305398 – Acorn Jul 30 '18 at 10:51