gbadev.org forum archive

This is a read-only mirror of the content originally found on forum.gbadev.org (now offline), salvaged from Wayback machine copies. A new forum can be found here.

DS development > file to memory

#163850 - hacker013 - Mon Oct 13, 2008 7:30 pm

hey everybody,

How do I read a File to memory and that it located memory if i not give a pointer to an existing located memory? A code example please.

gr,

hacker013
_________________
Website / Blog

Let the nds be with you.

#163852 - tepples - Mon Oct 13, 2008 8:00 pm

Is the size of the file (in bytes) known in advance?
_________________
-- Where is he?
-- Who?
-- You know, the human.
-- I think he moved to Tilwick.

#163855 - hacker013 - Mon Oct 13, 2008 8:55 pm

no
_________________
Website / Blog

Let the nds be with you.

#163857 - Lazy1 - Mon Oct 13, 2008 9:24 pm

You can get the file size by calling stat() and checking the st_size member of the stat struct you passed.

Example:
Code:

#include <sys/stat.h>

void Blah( void ) {
   struct stat st;

   if ( stat( "your_file_name", &st ) == 0 ) {
      // st.st_size contains the file size in bytes
      // Do stuff here
   }
}


Once you have your file size you can allocate the required memory using malloc() and read it in using fopen(), fread(), ect...

#163858 - elhobbs - Mon Oct 13, 2008 9:27 pm

Code:
FILE* pFile;
unsigned char *file_data;
size_t file_size;

//open the file
pFile = fopen(file_name,"rb");
if(pFile == 0)
{
   //unable to open file
   //do something
}
   
//find the file length
fseek (pFile, 0, SEEK_END);
file_size = ftell(pFile);

//alocate a buffer to hold the data
file_data = (unsigned char *) malloc (file_size);

//reset the file position
fseek (pFile, 0, SEEK_SET);

//read the data into the buffer
fread (file_data, 1, file_size, pFile);

//close the file
fclose (pFile);
here is some code to read a file into a dynamically allocated buffer. you will probably want to add some error checking code...

#163871 - Lazy1 - Tue Oct 14, 2008 3:37 am

You don't need to seek to the end of the file to get the length though, you can call fstat which is the same as stat() but works on an already opened file handle.