Contrib: SDL_RWFromZip

Hello ppl,

this is a small contribution to you all.

SDL_RWFromZip is used to read from ZIP files, so you can store all your
files in one compressed .ZIP (or .PAK, or whatever)

required: zlib and unzip.c & unzip.h provided with zlib
(ftp://ftp.freesoftware.com/pub/infozip/zlib/zlib.html)---------------------------------------------------------------

/*
Create a RWop from a file in a zip
pak is the name of the .ZIP
filename is the name of the file in the .ZIP

ex. SDL_RWFromZip(“data.zip”,“test.bmp”);
*/
SDL_RWops * SDL_RWFromZip(char * pak, char * filename)
{
void * zip;
int size;
SDL_RWops * rw;

zip = unzOpen(pak);
if (zip==NULL)
return NULL;

if (unzLocateFile(zip,filename,2) != UNZ_OK)
return NULL;

unz_file_info info;
unzGetCurrentFileInfo(zip,&info,NULL,0,NULL,0,NULL,0);
size=info.uncompressed_size;

if (unzOpenCurrentFile(zip) != UNZ_OK)
return NULL;

Uint8* buffer;
buffer = (Uint8*) malloc(size);

int result;
result = unzReadCurrentFile(zip,buffer,size);
rw = SDL_RWFromMem(buffer,size);

if (size!=result)
return NULL;

unzCloseCurrentFile(zip);

unzClose(zip);
return rw;
}

/*
Create a RWop from a file in a zip

the string you pass to this function is formated as follow:
SDL_RWFromZip(“zip:data.zip,test.bmp”);

if you do : SDL_RWFromZip(“test.bmp”) this will create a file RWop
*/
SDL_RWops * SDL_RWFromZip(char * str)
{
char temp[5];
SDL_RWops * rw=NULL;

strncpy(temp,str,4);
temp[4]=0;

if (stricmp(temp,“zip:”)==0)
{
// Packed file
char * p;
char pak[4096];
char file[4096];

strcpy(pak,str+4);
p=strrchr(pak,',');
if (p)
{
  *p=0;
  strcpy(file,p+1);
  rw = SDL_RWFromZip(pak,file);
}

}
else
{
// Normal File
rw = SDL_RWFromFile(str,“rb”);
}
return rw;
}


Gautier Portet
http://www.TLK.fr