Accessing files as an array in C++?

Programming, for all ages and all languages.
Post Reply
Perica
Member
Member
Posts: 454
Joined: Sat Nov 25, 2006 12:50 am

Accessing files as an array in C++?

Post by Perica »

..
Last edited by Perica on Sun Dec 03, 2006 9:09 pm, edited 2 times in total.
Tim

Re:Accessing files as an array in C++?

Post by Tim »

Memory-mapped files.

Under Windows, you do:
CreateFile (open the file)
CreateFileMapping (create a file mapping object on the file)
MapViewOfFile (open a memory window into the file mapping object)
Access the file as an array
UnMapViewOfFile
CloseHandle(file_mapping)
CloseHandle(file)
Perica
Member
Member
Posts: 454
Joined: Sat Nov 25, 2006 12:50 am

Re:Accessing files as an array in C++?

Post by Perica »

..
Last edited by Perica on Sun Dec 03, 2006 9:09 pm, edited 1 time in total.
Tim

Re:Accessing files as an array in C++?

Post by Tim »

You have no choice but to use the Win32 API for this, as the C standard library doesn't include memory-mapped files.

However, you can use fopen/fread/fwrite/fclose/fseek to do 'normal' file I/O under standard C. They come from the <stdio.h> file. Alternatively, you can use the C++ library; look up the std::ifstream and std::ofstream classes.
Andrew_Baker

Re:Accessing files as an array in C++?

Post by Andrew_Baker »

If you're using C++, can't you build an array of file _objects_? I'm not too sure of the implementation, but that's what I would suggest.

or could it be as simple as f_array[x]=fopen("whatever","r")?
Perica
Member
Member
Posts: 454
Joined: Sat Nov 25, 2006 12:50 am

Re:Accessing files as an array in C++?

Post by Perica »

..
Last edited by Perica on Sun Dec 03, 2006 9:09 pm, edited 1 time in total.
Tim

Re:Accessing files as an array in C++?

Post by Tim »

Sure, but memory-mapped files are far more efficient, especially for larger files.

Why do you need all of the file in memory at once? What's stopping you reading only what's needed?
Perica
Member
Member
Posts: 454
Joined: Sat Nov 25, 2006 12:50 am

Re:Accessing files as an array in C++?

Post by Perica »

..
Last edited by Perica on Sun Dec 03, 2006 9:09 pm, edited 1 time in total.
Post Reply