Reputation: 146
I would like to access a file as you would an array, rather than use fopen() and fgetc()/fputc() etc.
I'm looking for a method that will give me a pointer to the file which I can then treat as a big string(EOF terminated or a given length, whatever), I want the whole file in memory and need fast access to specific sections.
Is this possible? If so could you recommend a method? I'm also curious why this is not the default way of accessing files in c, is it because files are not generally stored in contiguous memory?
thanks for your help.
Upvotes: 0
Views: 245
Reputation: 182619
You are looking for something called memory-mapped files. For example, if you're on Unix, look for mmap
.
fd = open(...);
p = mmap(NULL, buf.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
/* Use `p` like a pointer to some memory and fstat to find size. */
If you're on Win32 look for CreateFileMapping
and MapViewOfFile
.
Upvotes: 3