1

I need to access the files with more pointers, i know the function fread and i know what it does but i need something like that:
access the file with more pointers

And i have to be able to do something like this:
move the pointer foward or back in the file data

One way could be open 3 time with 3 different FILE pointers the same file (but i think it's a dirty work) so i would like to know if there is a way to read a file with multi-pointers and decide to switch to the next byte or to the back byte with the pointer that i want.

Giovanni Far
  • 1,623
  • 6
  • 23
  • 37
  • Use `ftell` to get a reference to the current position of a stream, and `fseek` to go back to that location later – M.M Aug 10 '14 at 22:43
  • If you want to access the same file through different `FILE` objects, that'll be at least non-portable. Why do you want to do that? – mafso Aug 10 '14 at 22:44
  • @mafso: Is it really non-portable? I assumed it would work everywhere, at least if you only do reading. – Dietrich Epp Aug 10 '14 at 22:48
  • @DietrichEpp: It's implementation-defined (C11 7.19.3 p.8). I don't know, for what systems this doesn't work (and how important the systems where it doesn't are), though. – mafso Aug 10 '14 at 23:01
  • i need that because i'm implementing LZ77 algorithm so i need more pointer in the file to manage the buffer of the dictionary – Giovanni Far Aug 10 '14 at 23:14

1 Answers1

7

Option 1: open the file multiple times

This is totally fine. It's not dirty. The operating system and standard library will keep everything straight for you (as long as you're not also writing).

Option 2: read the entire file

This is also totally fine. Most files are small and fit in memory, then you can just use ordinary pointers to point to memory locations.

Option 3: memory map the entire file

On Unix-like systems, you can use mmap(). This will put the entire file in your address space, but the OS will typically defer actual IO until you read from a particular page in the memory map. This has most of the advantages of options 1 and 2, but it is slightly more complicated to work with, and you would need to write a separate version for Windows, because Windows doesn't have mmap() (it has something else, I forget what it's called).

Option 4: seek back and forth

You can save your position with ftell() and then fseek() later to get back.

Dietrich Epp
  • 205,541
  • 37
  • 345
  • 415
  • 1
    (You were thinking of [MapViewOfFile](http://stackoverflow.com/questions/4087282/is-there-a-memory-mapping-api-on-windows-platform-just-like-mmap-on-linux).) – Jongware Aug 10 '14 at 22:51
  • thank you... i think i will use the first option... because i'm implementing the LZ77 algorithm and with the option 1 (for me) is more easier – Giovanni Far Aug 10 '14 at 23:15