コード例 #1
0
            fileHandleZipStreaming(const file_entry* entry, const Zips& z): _cpos(0)
            {
                int r = 0;
                r = unzGoToFilePos(entry->zp, const_cast<unz_file_pos*>(&entry->pos));
                OX_ASSERT(r == UNZ_OK);

                r = unzOpenCurrentFile(entry->zp);
                OX_ASSERT(r == UNZ_OK);


                void* ptr;
                r = unzRealTell(entry->zp, &_pos, &_size, &ptr);
                OX_ASSERT(r == UNZ_OK);

                zlib_filefunc_def* f = (zlib_filefunc_def*)ptr;
                const char* ssss = z.getZipFileName((int)(size_t)f->opaque);

                _h = file::open(ssss, "rb");
                file::seek(_h, static_cast<unsigned int>(_pos), SEEK_SET);

                unzCloseCurrentFile(entry->zp);
            }
コード例 #2
0
void FileUtils::extractFromZip(const char* zipFilePath, const char* src, const char* dest) throw (IOException)
{
	unzFile zipFile = unzOpen(zipFilePath);
	int result = unzLocateFile(zipFile,src,0);
	if (result == UNZ_OK)
	{
		// found a match which is now the current file
		unzOpenCurrentFile(zipFile);
		const int chunkSize = 4096;
		char buffer[chunkSize];

		std::ofstream outputFile(dest,std::ofstream::binary);
		if (!outputFile.good())
		{
			throw IOException("Unable to write to file " + std::string(dest));
		}
		while (true)
		{
			int count = unzReadCurrentFile(zipFile,buffer,chunkSize);
			if (count <= 0)
			{
				if (count < 0)
				{
					throw IOException("Error extracting file from archive " + std::string(src));
				}
				break;
			}
			outputFile.write(buffer,count);
		}
		outputFile.close();

		unzCloseCurrentFile(zipFile);
	}
	else
	{
		throw IOException("Unable to find file " + std::string(src) + " in zip archive " + std::string(zipFilePath));
	}
	unzClose(zipFile);
}
コード例 #3
0
	//-----------------------------------------------------------------//
	bool unzip::create_file(uint32_t index, const std::string& filename)
	{
		if(index < static_cast<uint32_t>(files_.size())) {
			unzSetOffset(hnd_, files_[index].ofs_);

			if(unzOpenCurrentFile(hnd_) != UNZ_OK) return false;

			utils::file_io fout;
			fout.open(filename, "wb");

			char buff[4096];
			uLong sz;
			while((sz = unzReadCurrentFile(hnd_, buff, sizeof(buff))) > 0) {
				fout.write(buff, 1, sz);
			}
			unzCloseCurrentFile(hnd_);
			fout.close();

			return true;
		}
		return false;
	}
コード例 #4
0
ファイル: fileutils.cpp プロジェクト: iebie/DualBootPatcher
bool FileUtils::mzReadToMemory(unzFile uf,
                               std::vector<unsigned char> *output,
                               void (*cb)(uint64_t bytes, void *), void *userData)
{
    unz_file_info64 fi;

    if (!mzGetInfo(uf, &fi, nullptr)) {
        return false;
    }

    std::vector<unsigned char> data;
    data.reserve(fi.uncompressed_size);

    int ret = unzOpenCurrentFile(uf);
    if (ret != UNZ_OK) {
        return false;
    }

    int n;
    char buf[32768];

    while ((n = unzReadCurrentFile(uf, buf, sizeof(buf))) > 0) {
        if (cb) {
            cb(data.size() + n, userData);
        }

        data.insert(data.end(), buf, buf + n);
    }

    unzCloseCurrentFile(uf);

    if (n != 0) {
        return false;
    }

    data.swap(*output);
    return true;
}
コード例 #5
0
ファイル: fileutils.cpp プロジェクト: iebie/DualBootPatcher
bool FileUtils::mzExtractFile(unzFile uf,
                              const std::string &directory)
{
    unz_file_info64 fi;
    std::string filename;

    if (!mzGetInfo(uf, &fi, &filename)) {
        return false;
    }

    std::string fullPath(directory);
    fullPath += "/";
    fullPath += filename;

    boost::filesystem::path path(fullPath);
    boost::filesystem::create_directories(path.parent_path());

    std::ofstream file(fullPath, std::ios::binary);
    if (file.fail()) {
        return false;
    }

    int ret = unzOpenCurrentFile(uf);
    if (ret != UNZ_OK) {
        return false;
    }

    int n;
    char buf[32768];

    while ((n = unzReadCurrentFile(uf, buf, sizeof(buf))) > 0) {
        file.write(buf, n);
    }

    unzCloseCurrentFile(uf);

    return n == 0;
}
コード例 #6
0
unsigned char *ZipFile::getFileData(const std::string &fileName, unsigned long *pSize)
{
    unsigned char * pBuffer = NULL;
    if (pSize)
    {
        *pSize = 0;
    }

    do
    {
        CC_BREAK_IF(!m_data->zipFile);
        CC_BREAK_IF(fileName.empty());

        ZipFilePrivate::FileListContainer::const_iterator it = m_data->fileList.find(fileName);
        CC_BREAK_IF(it ==  m_data->fileList.end());

        ZipEntryInfo fileInfo = it->second;

        int nRet = unzGoToFilePos(m_data->zipFile, &fileInfo.pos);
        CC_BREAK_IF(UNZ_OK != nRet);

        nRet = unzOpenCurrentFile(m_data->zipFile);
        CC_BREAK_IF(UNZ_OK != nRet);

        pBuffer = new unsigned char[fileInfo.uncompressed_size];
        int nSize = 0;
        nSize = unzReadCurrentFile(m_data->zipFile, pBuffer, fileInfo.uncompressed_size);
        CCAssert(nSize == 0 || nSize == (int)fileInfo.uncompressed_size, "the file size is wrong");

        if (pSize)
        {
            *pSize = fileInfo.uncompressed_size;
        }
        unzCloseCurrentFile(m_data->zipFile);
    } while (0);

    return pBuffer;
}
コード例 #7
0
ファイル: zip.c プロジェクト: armornick/duktape-misc
static duk_ret_t dukzip_unz_readfile(duk_context *ctx) {
	unz_file_info fileInfo;
	unzFile archive = dukzip_unz_from_this(ctx);
	int ret = UNZ_OK;

	unzGetCurrentFileInfo(archive, &fileInfo, NULL, 0, NULL, 0, NULL, 0);
	void *bytes = duk_push_fixed_buffer(ctx, fileInfo.uncompressed_size);

	ret = unzOpenCurrentFile(archive);
	if (ret != UNZ_OK) {
		duk_error(ctx, DUK_ERR_INTERNAL_ERROR, "unable to open file in archive");
		return -1;
	}

	ret = unzReadCurrentFile(archive, bytes, fileInfo.uncompressed_size);
	if (ret < 0) {
		duk_error(ctx, DUK_ERR_INTERNAL_ERROR, "unable to read file in archive");
		return -1;
	}
	unzCloseCurrentFile(archive);

	return 1;
}
コード例 #8
0
ファイル: zipreader.cpp プロジェクト: GunioRobot/quickdev16
ZipReader::ZipReader(const char *fn) : filesize(0), zipready(false) {
    unz_file_info cFileInfo;  //Create variable to hold info for a compressed file
    char cFileName[sizeof(cname)];

    if(zipfile = unzOpen(fn)) {  //Open zip file
        for(int cFile = unzGoToFirstFile(zipfile); cFile == UNZ_OK; cFile = unzGoToNextFile(zipfile)) {
            //Gets info on current file, and places it in cFileInfo
            unzGetCurrentFileInfo(zipfile, &cFileInfo, cFileName, sizeof(cname), 0, 0, 0, 0);

            //verify uncompressed file is not bigger than max ROM size
            if((cFileInfo.uncompressed_size <= 0x1000000 + 512) && (cFileInfo.uncompressed_size > filesize)) {
                strcpy(cname, cFileName);
                filesize = cFileInfo.uncompressed_size;
            }
        }

        if(filesize) {
            unzLocateFile(zipfile, cname, 1);
            unzOpenCurrentFile(zipfile);
            zipready = true;
        }
    }
}
コード例 #9
0
ファイル: utils.cpp プロジェクト: kangaroo/moon
gboolean
managed_unzip_stream_to_stream (ManagedStreamCallbacks *source, ManagedStreamCallbacks *dest, const char *partname)
{
	zlib_filefunc_def funcs;
	unzFile zipFile;
	gboolean ret;

	ret = FALSE;

	funcs.zopen_file = managed_stream_open;
	funcs.zread_file = managed_stream_read;
	funcs.zwrite_file = managed_stream_write;
	funcs.ztell_file = managed_stream_tell;
	funcs.zseek_file = managed_stream_seek;
	funcs.zclose_file = managed_stream_close;
	funcs.zerror_file = managed_stream_error;
	funcs.opaque = source;

	zipFile = unzOpen2 (NULL, &funcs);

	if (!zipFile)
		return FALSE;

	if (unzLocateFile (zipFile, partname, 2) != UNZ_OK)
		goto cleanup;	

	if (unzOpenCurrentFile (zipFile) != UNZ_OK)
		goto cleanup;

	ret = managed_unzip_extract_to_stream (zipFile, dest);

cleanup:
	unzCloseCurrentFile (zipFile);
	unzClose (zipFile);

	return ret;
}
コード例 #10
0
ファイル: CCZipFile.cpp プロジェクト: gooderman/vv2d
unsigned char* CCZipFile::getFileDataNoOrder(const char *fileName, unsigned long *pSize)
{
    unsigned char * pBuffer = NULL;
    if (pSize)
    {
        *pSize = 0;
    }    
    do
    {
        CC_BREAK_IF(!m_zipFile);
        CC_BREAK_IF(m_fileList.empty());
        
        std::map<std::string, struct __ZipEntryInfo>::const_iterator it = m_fileList.find(fileName);
        CC_BREAK_IF(it ==  m_fileList.end());
        
        __ZipEntryInfo fileInfo = it->second;
        
        int nRet = unzGoToFilePos(m_zipFile, &fileInfo.pos);
        CC_BREAK_IF(UNZ_OK != nRet);
        
        nRet = unzOpenCurrentFile(m_zipFile);
        CC_BREAK_IF(UNZ_OK != nRet);
        //MARK unfinish process big file
        pBuffer = new unsigned char[fileInfo.uncompressed_size];
        int CC_UNUSED nSize = unzReadCurrentFile(m_zipFile, pBuffer, fileInfo.uncompressed_size);
        CCAssert(nSize == 0 || nSize == (int)fileInfo.uncompressed_size, "the file size is wrong");
        
        if (pSize)
        {
            *pSize = fileInfo.uncompressed_size;
        }
        unzCloseCurrentFile(m_zipFile);
    } while (0);
    
    return pBuffer;

}
コード例 #11
0
ファイル: XSync20Zip_API.c プロジェクト: SoongChoi/anywall
int XSYNCZIP_getEntryDataByName ( XDRM_CTRL_CONTEXT_PTR pCtx,  char *name, char *buffer )
{
   int retval =0;

#if 0
   // before info
   unz_file_info64 cur_file_infoSaved;
   unz_file_info64_internal cur_file_info_internalSaved;
   ZPOS64_T num_fileSaved;
   ZPOS64_T pos_in_central_dirSaved;

   /* Save the current state */
   num_fileSaved = s->num_file;
   pos_in_central_dirSaved = s->pos_in_central_dir;
   cur_file_infoSaved = s->cur_file_info;
   cur_file_info_internalSaved = s->cur_file_info_internal;
#endif

   if ( unzLocateFile ( pCtx->pZipFile,name,0/*CASESENSITIVITY*/ ) !=UNZ_OK ) {
      retval= -1;
   } else {
      retval = unzOpenCurrentFile ( pCtx->pZipFile );
      if ( retval == UNZ_OK ) {
#if 0
         retval =unzReadCurrentFile ( pCtx->pZipFile, buffer, ( unsigned int ) pCtx->pZipFile->cur_file_info.uncompressed_size );
#else
         retval =unzReadEntry ( pCtx->pZipFile, buffer, 0, ( unsigned int ) pCtx->pZipFile->cur_file_info.uncompressed_size, Z_FINISH );
#endif
      } else {
         retval =-1;
      }
   }

   unzCloseCurrentFile ( pCtx->pZipFile );
   return retval;

}
コード例 #12
0
ファイル: file_access_zip.cpp プロジェクト: baekdahl/godot
unzFile ZipArchive::get_file_handle(String p_file) const {

	ERR_FAIL_COND_V(!file_exists(p_file), NULL);
	File file = files[p_file];

	FileAccess* f = FileAccess::open(packages[file.package].filename, FileAccess::READ);
	ERR_FAIL_COND_V(!f, NULL);

	zlib_filefunc_def io;
	zeromem(&io, sizeof(io));

	io.opaque = f;
	io.zopen_file = godot_open;
	io.zread_file = godot_read;
	io.zwrite_file = godot_write;

	io.ztell_file = godot_tell;
	io.zseek_file = godot_seek;
	io.zclose_file = godot_close;
	io.zerror_file = godot_testerror;

	io.alloc_mem = godot_alloc;
	io.free_mem = godot_free;

	unzFile pkg = unzOpen2(packages[file.package].filename.utf8().get_data(), &io);
	ERR_FAIL_COND_V(!pkg, NULL);
	int unz_err = unzGoToFilePos(pkg, &file.file_pos);
	ERR_FAIL_COND_V(unz_err != UNZ_OK, NULL);
	if (unzOpenCurrentFile(pkg) != UNZ_OK) {

		unzClose(pkg);
		ERR_FAIL_V(NULL);
	};

	return pkg;
};
コード例 #13
0
bool eFileTypeZIP::OpenCurrent(unzFile h, char* name) const
{
	unz_file_info fi;
	char n[xIo::MAX_PATH_LEN];
	if(unzGetCurrentFileInfo(h, &fi, n, xIo::MAX_PATH_LEN, NULL, 0, NULL, 0) != UNZ_OK)
		return false;
	const eFileType* t = eFileType::FindByName(n);
	if(!t)
		return false;
	if(unzOpenCurrentFile(h) != UNZ_OK)
		return false;

	bool ok = false;
	byte* buf = new byte[fi.uncompressed_size];
	if(unzReadCurrentFile(h, buf, fi.uncompressed_size) == int(fi.uncompressed_size))
	{
		ok = t->Open(buf, fi.uncompressed_size);
		if(ok && name)
			strcpy(name, n);
	}
	SAFE_DELETE_ARRAY(buf);
	unzCloseCurrentFile(h);
	return ok;
}
コード例 #14
0
ファイル: blocks.c プロジェクト: 1taplay/winbolo
// Size in MB
bool blocksCreate(char *fileName, int size) {
  bool returnValue = TRUE;
  blockKey = 0;
  
  logMaxMemory = size * 2;
  if (logMaxMemory < 2) {
    logMaxMemory = 2;
  }

  block = NULL;
  logFile = NULL;
  logMinBlockPosition = 0;
  logMaxBlockPosition = 0;

  logPosition = 0;
  zipFilePosition = 0;
  logFile = unzOpen(fileName);
  if (logFile == NULL) {
    returnValue = FALSE;
  }

  if (returnValue == TRUE) {
    strcpy(logFileName, fileName);
    if (unzLocateFile(logFile, "log.dat", 0) != UNZ_OK) {
      returnValue = FALSE;
    }
  }

  if (returnValue == TRUE) {
    if (unzOpenCurrentFile(logFile) != UNZ_OK) {
      returnValue = FALSE;
    }
  }

  return returnValue;
}
コード例 #15
0
ファイル: unzip.cpp プロジェクト: luaman/modplug
bool CZipArchive::ExtractFile(std::size_t index)
//----------------------------------------------
{
	if(index >= contents.size())
	{
		return false;
	}

	data.clear();

	unz_file_pos bestFile;
	unz_file_info info;

	bestFile.pos_in_zip_directory = static_cast<uLong>(contents[index].cookie1);
	bestFile.num_of_file = static_cast<uLong>(contents[index].cookie2);

	if(unzGoToFilePos(zipFile, &bestFile) == UNZ_OK && unzOpenCurrentFile(zipFile) == UNZ_OK)
	{
		unzGetCurrentFileInfo(zipFile, &info, nullptr, 0, nullptr, 0, nullptr, 0);
		
		try
		{
			data.resize(info.uncompressed_size);
		} catch(...)
		{
			unzCloseCurrentFile(zipFile);
			return false;
		}
		unzReadCurrentFile(zipFile, &data[0], info.uncompressed_size);
		unzCloseCurrentFile(zipFile);

		return true;
	}

	return false;
}
コード例 #16
0
ファイル: unz.c プロジェクト: Protovision/io-lua
static void	unz_extract(void **ptr, size_t *size, const char *filename)
{
	unz_file_info info;
	char *data, *data_end;
	int got;

	if (!unz_exists(filename))
		FATAL("Failed to locate packaged file: %s", filename);

	if (unzOpenCurrentFile(foundzip) != UNZ_OK)
		FATAL("Failed to unpack %s", filename);

	unzGetCurrentFileInfo(foundzip, &info, NULL, 0, NULL, 0, NULL, 0);
	data = (char*)malloc(info.uncompressed_size+1);
	*ptr = data;
	*size = info.uncompressed_size;
	data_end = data + info.uncompressed_size;
	*data_end = 0;

	while ((got = unzReadCurrentFile(foundzip, data, data_end - data)) > 0) {
		data = data + got;	
	}
	unzCloseCurrentFile(foundzip);
}
コード例 #17
0
ファイル: apklib.c プロジェクト: raimue/apkenv
enum ApkResult
apk_uncompress_internal(AndroidApk *apk, char **buffer, size_t *size)
{
    zlib_filefunc_def filefunc;
    fill_memory_filefunc(&filefunc);
    char *old_buffer = *buffer;
    char path[1024];
    sprintf(path, "%x+%x", *buffer, *size);

    /* Decompress a single file in a .zip from memory */
    unz_file_info info;
    unzFile *unz = unzOpen2(path, &filefunc);
    unzGoToFirstFile(unz);
    unzGetCurrentFileInfo(unz, &info, NULL, 0, NULL, 0, NULL, 0);
    *size = info.uncompressed_size;
    *buffer = malloc(*size);
    unzOpenCurrentFile(unz);
    unzReadCurrentFile(unz, *buffer, *size);
    unzCloseCurrentFile(unz);
    unzClose(unz);
    free(old_buffer);

    return APK_OK;
}
コード例 #18
0
ファイル: driver.c プロジェクト: joshdekock/jim-pspware
SDL_bool dr_load_section(unzFile *gz, SECTION s, Uint8 *current_buf) {
    LIST *l;
    for(l=s.item;l;l=l->next) {
	SECTION_ITEM *item=l->data;
    
	if (strcmp(item->filename,"-")!=0) {
	    /* nouveau fichier, on l'ouvre */
	    if (unzLocateFile(gz, item->filename, 2) == UNZ_END_OF_LIST_OF_FILE) {
		unzClose(gz);
		return SDL_FALSE;
	    }
	    if (unzOpenCurrentFile(gz) != UNZ_OK) {
		unzClose(gz);
		return SDL_FALSE;
	    }
	}
	create_progress_bar(item->filename);
	if (item->type==LD_ALTERNATE)
	    zfread_alternate(gz, current_buf + item->begin, item->size, 2);
	else
	    zfread(gz, current_buf + item->begin, item->size);
    }
    return SDL_TRUE;
}
コード例 #19
0
ファイル: Unpak.cpp プロジェクト: gthgame/gth
int PackFileGetFileWithIndex (packfile_t *pf, int idx , char **buf)
{
	DWORD	err;
	
	if (idx >= (int)pf->gi.number_entry)
		return ERROR_FILE_NOT_EXIST;
	
	*buf = (char *)malloc (pf->fi[idx].size);

	unzLocateFileMy (pf->uf, idx, pf->fi[idx].c_offset);

	unzOpenCurrentFile (pf->uf);
	err = unzReadCurrentFile (pf->uf,*buf,pf->fi[idx].size);
	unzCloseCurrentFile (pf->uf);

	if (err!=pf->fi[idx].size)
	{
		free (*buf);
		*buf = NULL;
		return ERROR_FILE_NOT_EXTRACTED;
	}

	return pf->fi[idx].size;
}
コード例 #20
0
	char* Zip::getFileData(const char* filename, unsigned long& size)
	{
		char * pBuffer = NULL;

		auto it = _files.find(filename);

		if (it == _files.end()) return NULL;

		ZipEntryInfo fileInfo = it->second;

		int nRet = unzGoToFilePos(_zipFile, &fileInfo.pos);
		if (UNZ_OK != nRet) return NULL;

		nRet = unzOpenCurrentFile(_zipFile);
		if (UNZ_OK != nRet) return NULL;

		pBuffer = new char[fileInfo.uncompressed_size];
		unzReadCurrentFile(_zipFile, pBuffer, fileInfo.uncompressed_size);

		size = fileInfo.uncompressed_size;
		unzCloseCurrentFile(_zipFile);

		return pBuffer;
	}
コード例 #21
0
void ExportTemplateManager::_install_from_file(const String &p_file, bool p_use_progress) {

	FileAccess *fa = NULL;
	zlib_filefunc_def io = zipio_create_io_from_file(&fa);

	unzFile pkg = unzOpen2(p_file.utf8().get_data(), &io);
	if (!pkg) {

		EditorNode::get_singleton()->show_warning(TTR("Can't open export templates zip."));
		return;
	}
	int ret = unzGoToFirstFile(pkg);

	int fc = 0; //count them and find version
	String version;

	while (ret == UNZ_OK) {

		unz_file_info info;
		char fname[16384];
		ret = unzGetCurrentFileInfo(pkg, &info, fname, 16384, NULL, 0, NULL, 0);

		String file = fname;

		if (file.ends_with("version.txt")) {

			Vector<uint8_t> data;
			data.resize(info.uncompressed_size);

			//read
			unzOpenCurrentFile(pkg);
			ret = unzReadCurrentFile(pkg, data.ptrw(), data.size());
			unzCloseCurrentFile(pkg);

			String data_str;
			data_str.parse_utf8((const char *)data.ptr(), data.size());
			data_str = data_str.strip_edges();

			// Version number should be of the form major.minor[.patch].status[.module_config]
			// so it can in theory have 3 or more slices.
			if (data_str.get_slice_count(".") < 3) {
				EditorNode::get_singleton()->show_warning(vformat(TTR("Invalid version.txt format inside templates: %s."), data_str));
				unzClose(pkg);
				return;
			}

			version = data_str;
		}

		if (file.get_file().size() != 0) {
			fc++;
		}

		ret = unzGoToNextFile(pkg);
	}

	if (version == String()) {
		EditorNode::get_singleton()->show_warning(TTR("No version.txt found inside templates."));
		unzClose(pkg);
		return;
	}

	String template_path = EditorSettings::get_singleton()->get_templates_dir().plus_file(version);

	DirAccess *d = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
	Error err = d->make_dir_recursive(template_path);
	if (err != OK) {
		EditorNode::get_singleton()->show_warning(TTR("Error creating path for templates:") + "\n" + template_path);
		unzClose(pkg);
		return;
	}

	memdelete(d);

	ret = unzGoToFirstFile(pkg);

	EditorProgress *p = NULL;
	if (p_use_progress) {
		p = memnew(EditorProgress("ltask", TTR("Extracting Export Templates"), fc));
	}

	fc = 0;

	while (ret == UNZ_OK) {

		//get filename
		unz_file_info info;
		char fname[16384];
		unzGetCurrentFileInfo(pkg, &info, fname, 16384, NULL, 0, NULL, 0);

		String file = String(fname).get_file();

		if (file.size() == 0) {
			ret = unzGoToNextFile(pkg);
			continue;
		}

		Vector<uint8_t> data;
		data.resize(info.uncompressed_size);

		//read
		unzOpenCurrentFile(pkg);
		unzReadCurrentFile(pkg, data.ptrw(), data.size());
		unzCloseCurrentFile(pkg);

		if (p) {
			p->step(TTR("Importing:") + " " + file, fc);
		}

		FileAccess *f = FileAccess::open(template_path.plus_file(file), FileAccess::WRITE);

		if (!f) {
			ret = unzGoToNextFile(pkg);
			fc++;
			ERR_CONTINUE(!f);
		}

		f->store_buffer(data.ptr(), data.size());

		memdelete(f);

		ret = unzGoToNextFile(pkg);
		fc++;
	}

	if (p) {
		memdelete(p);
	}

	unzClose(pkg);

	_update_template_list();
}
コード例 #22
0
ファイル: vfs.c プロジェクト: AEonZR/GtkRadiant
// NOTE: when loading a file, you have to allocate one extra byte and set it to \0
int vfsLoadFile (const char *filename, void **bufferptr, int index)
{
  int i, count = 0;
  char tmp[NAME_MAX], fixed[NAME_MAX];
  GSList *lst;
  
  // filename is a full path
  if (index == -1)
  {
    long len;
    FILE *f;
    
    f = fopen (filename, "rb");
    if (f == NULL)
      return -1;
    
    fseek (f, 0, SEEK_END);
    len = ftell (f);
    rewind (f);
    
    *bufferptr = safe_malloc (len+1);
    if (*bufferptr == NULL)
      return -1;
    
    fread (*bufferptr, 1, len, f);
    fclose (f);
    
    // we need to end the buffer with a 0
    ((char*) (*bufferptr))[len] = 0;
    
    return len;
  }
  
  *bufferptr = NULL;
  strcpy (fixed, filename);
  vfsFixDOSName (fixed);
  g_strdown (fixed);
  
  for (i = 0; i < g_numDirs; i++)
  {
    strcpy (tmp, g_strDirs[i]);
    strcat (tmp, filename);
    if (access (tmp, R_OK) == 0)
    {
      if (count == index)
      {
        long len;
        FILE *f;
        
        f = fopen (tmp, "rb");
        if (f == NULL)
          return -1;
        
        fseek (f, 0, SEEK_END);
        len = ftell (f);
        rewind (f);
        
        *bufferptr = safe_malloc (len+1);
        if (*bufferptr == NULL)
          return -1;
        
        fread (*bufferptr, 1, len, f);
        fclose (f);
        
        // we need to end the buffer with a 0
        ((char*) (*bufferptr))[len] = 0;
        
        return len;
      }
      
      count++;
    }
  }
  
  for (lst = g_pakFiles; lst != NULL; lst = g_slist_next (lst))
  {
    VFS_PAKFILE* file = (VFS_PAKFILE*)lst->data;
    
    if (strcmp (file->name, fixed) != 0)
      continue;
    
    if (count == index)
    {
      memcpy (file->zipfile, &file->zipinfo, sizeof (unz_s));
      
      if (unzOpenCurrentFile (file->zipfile) != UNZ_OK)
        return -1;
      
      *bufferptr = safe_malloc (file->size+1);
      // we need to end the buffer with a 0
      ((char*) (*bufferptr))[file->size] = 0;
      
      i = unzReadCurrentFile (file->zipfile , *bufferptr, file->size);
      unzCloseCurrentFile (file->zipfile);
      if (i < 0)
        return -1;
      else
        return file->size;
    }
    
    count++;
  }
  
  return -1;
}
コード例 #23
0
ファイル: ziphelper.c プロジェクト: CocoaMSX/CocoaMSX
/******************************************************************************
*** Description
***     Load a file in a zip file into memory.
***
*** Arguments
***     zipName     - Name of zip file
***     fileName    - Name of file insize zipfile to load
***     size        - Output of size of file
***
*** Return
***     Pointer to allocate memory buffer with file content or NULL on
***     failure.
***
*******************************************************************************
*/
void* _zipLoadFile(const char* zipName, const char* fileName, int* size, zlib_filefunc_def* filefunc)
{
    void* buf;
    char name[256];
    unzFile zip;
    unz_file_info info;

    *size = 0;

    if (fileName[0] == '*') {
        strcpy(name, zipName);
        name[strlen(zipName) - 3] = fileName[strlen(fileName) - 3];
        name[strlen(zipName) - 2] = fileName[strlen(fileName) - 2];
        name[strlen(zipName) - 1] = fileName[strlen(fileName) - 1];
    }
    else {
        strcpy(name, fileName);
    }

    zip = unzOpen2(zipName, filefunc);
    if (!zip) {
        return NULL;
    }

#ifdef __APPLE__
    // Most OS X installs are on a case-insensitive FS
    if (unzLocateFile(zip, name, 2) == UNZ_END_OF_LIST_OF_FILE) {
#else
    if (unzLocateFile(zip, name, 1) == UNZ_END_OF_LIST_OF_FILE) {
#endif
        unzClose(zip);
        return NULL;
    }

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

    unzGetCurrentFileInfo(zip,&info,NULL,0,NULL,0,NULL,0);

    buf = malloc(info.uncompressed_size);
    *size = info.uncompressed_size;

    if (!buf) {
        unzCloseCurrentFile(zip);
        unzClose(zip);
        return NULL;
    }

    unzReadCurrentFile(zip, buf, info.uncompressed_size);
    unzCloseCurrentFile(zip);
    unzClose(zip);

    return buf;
}


/******************************************************************************
*** Description
***     Read cache to speed-up reading multiple files from one zip.
***
******************************************************************************/

static char *cacheData = NULL, cacheFile[512];
static zlib_filefunc_def cacheFilefunc;

void* zipLoadFile(const char* zipName, const char* fileName, int* size)
{
    if (strncmp(zipName, "mem", 3) == 0) {
        return memFileLoad(zipName, fileName, size);
    }
    if( cacheData != NULL && *cacheFile != '\0' && 0==strcmp(cacheFile, zipName) ) {
        return _zipLoadFile(cacheData, fileName, size, &cacheFilefunc);
    }else{
        return _zipLoadFile(zipName, fileName, size, NULL);
    }
}

void zipCacheReadOnlyZip(const char* zipName)
{
    if (zipName != NULL && strncmp(zipName, "mem", 3) == 0) {
        return;
    }

    *cacheFile = '\0';
    if( cacheData != NULL ) {
        free(cacheData);
        cacheData = NULL;
        free_fopen_memfunc(&cacheFilefunc);
    }
    if( zipName != NULL ) {
        FILE *file;
        file = fopen(zipName, "rb");
        if( file != NULL ) {
            unsigned int filesize;
            fseek(file, 0, SEEK_END);
            filesize = ftell(file);
            fill_fopen_memfunc(&cacheFilefunc, filesize);
            fseek(file, 0, SEEK_SET);
            cacheData = malloc(filesize);
            if( cacheData != NULL ) {
                size_t size = fread(cacheData, 1, filesize, file);
                if( size == filesize ) {
                    strcpy(cacheFile, zipName);
                }
            }
            fclose(file);
        }
    }
}


/******************************************************************************
*** Description
***     Load a file in a zip file into memory.
***
*** Arguments
***     zipName     - Name of zip file
***     fileName    - Name of file insize zipfile to save
***     buffer      - Buffer to save
***     size        - Size of buffer to save
***
*******************************************************************************
*/
int zipSaveFile(const char* zipName, const char* fileName, int append, void* buffer, int size)
{
    zipFile zip;
    zip_fileinfo zi;
    int err;

    if (strncmp(zipName, "mem", 3) == 0) {
        return memFileSave(zipName, fileName, append, buffer, size);
    }

    zip = zipOpen(zipName, append ? 2 : 0);
    if (zip == NULL) {
        return 0;
    }

    memset(&zi, 0, sizeof(zi));

    err = zipOpenNewFileInZip(zip, fileName, &zi,
                              NULL, 0, NULL, 0, NULL,
                              Z_DEFLATED, Z_DEFAULT_COMPRESSION);
    if (err == ZIP_OK) {
        err = zipWriteInFileInZip(zip, buffer, size);
    }

    zipClose(zip, NULL);

    return err >= 0;
}
コード例 #24
0
ファイル: UnCompressZip.cpp プロジェクト: XyzalZhang/SPlayer
unzFile UnCompressZip::unzOpenInternal (const void *path,
                               zlib_filefunc64_32_def* pzlib_filefunc64_32_def,
                               int is64bitOpenFunction)
{
    unz64_s us;
    unz64_s *s;
    ZPOS64_T central_pos;
    uLong   uL;

    uLong number_disk;          /* number of the current dist, used for
                                   spaning ZIP, unsupported, always 0*/
    uLong number_disk_with_CD;  /* number the the disk with central dir, used
                                   for spaning ZIP, unsupported, always 0*/
    ZPOS64_T number_entry_CD;      /* total number of entries in
                                   the central dir
                                   (same than number_entry on nospan) */

    int err=UNZ_OK;

    //if (unz_copyright[0]!=' ')
        //return NULL;

    us.z_filefunc.zseek32_file = NULL;
    us.z_filefunc.ztell32_file = NULL;
    if (pzlib_filefunc64_32_def==NULL)
        fill_fopen64_filefunc(&us.z_filefunc.zfile_func64);
    else
        us.z_filefunc = *pzlib_filefunc64_32_def;
    us.is64bitOpenFunction = is64bitOpenFunction;

    us.filestream = ZOPEN64(us.z_filefunc, path, ZLIB_FILEFUNC_MODE_READ | ZLIB_FILEFUNC_MODE_EXISTING);
    if (us.filestream==NULL)
        return NULL;

    central_pos = unz64local_SearchCentralDir64(&us.z_filefunc,us.filestream);
    if (central_pos)
    {
       uLong uS;
       ZPOS64_T uL64;

       us.isZip64 = 1;

       if (ZSEEK64(us.z_filefunc, us.filestream, central_pos,ZLIB_FILEFUNC_SEEK_SET)!=0)
         err=UNZ_ERRNO;

       if (unz64local_getLong(&us.z_filefunc, us.filestream,&uL)!=UNZ_OK)
         err=UNZ_ERRNO;

        
       if (unz64local_getLong64(&us.z_filefunc, us.filestream,&uL64)!=UNZ_OK)
         err=UNZ_ERRNO;

        
       if (unz64local_getShort(&us.z_filefunc, us.filestream,&uS)!=UNZ_OK)
            err=UNZ_ERRNO;

        
        if (unz64local_getShort(&us.z_filefunc, us.filestream,&uS)!=UNZ_OK)
            err=UNZ_ERRNO;

        
        if (unz64local_getLong(&us.z_filefunc, us.filestream,&number_disk)!=UNZ_OK)
            err=UNZ_ERRNO;

       
        if (unz64local_getLong(&us.z_filefunc, us.filestream,&number_disk_with_CD)!=UNZ_OK)
            err=UNZ_ERRNO;

        
        if (unz64local_getLong64(&us.z_filefunc, us.filestream,&us.gi.number_entry)!=UNZ_OK)
            err=UNZ_ERRNO;

        
        if (unz64local_getLong64(&us.z_filefunc, us.filestream,&number_entry_CD)!=UNZ_OK)
            err=UNZ_ERRNO;

        if ((number_entry_CD!=us.gi.number_entry) ||
            (number_disk_with_CD!=0) ||
            (number_disk!=0))
            err=UNZ_BADZIPFILE;

        
        if (unz64local_getLong64(&us.z_filefunc, us.filestream,&us.size_central_dir)!=UNZ_OK)
            err=UNZ_ERRNO;

        
        if (unz64local_getLong64(&us.z_filefunc, us.filestream,&us.offset_central_dir)!=UNZ_OK)
            err=UNZ_ERRNO;

        us.gi.size_comment = 0;
    }
    else
    {
        central_pos = unz64local_SearchCentralDir(&us.z_filefunc,us.filestream);
        if (central_pos==0)
            err=UNZ_ERRNO;

        us.isZip64 = 0;

        if (ZSEEK64(us.z_filefunc, us.filestream,
                                        central_pos,ZLIB_FILEFUNC_SEEK_SET)!=0)
            err=UNZ_ERRNO;

        
        if (unz64local_getLong(&us.z_filefunc, us.filestream,&uL)!=UNZ_OK)
            err=UNZ_ERRNO;

       
        if (unz64local_getShort(&us.z_filefunc, us.filestream,&number_disk)!=UNZ_OK)
            err=UNZ_ERRNO;

        
        if (unz64local_getShort(&us.z_filefunc, us.filestream,&number_disk_with_CD)!=UNZ_OK)
            err=UNZ_ERRNO;

        
        if (unz64local_getShort(&us.z_filefunc, us.filestream,&uL)!=UNZ_OK)
            err=UNZ_ERRNO;
        us.gi.number_entry = uL;

       
        if (unz64local_getShort(&us.z_filefunc, us.filestream,&uL)!=UNZ_OK)
            err=UNZ_ERRNO;
        number_entry_CD = uL;

        if ((number_entry_CD!=us.gi.number_entry) ||
            (number_disk_with_CD!=0) ||
            (number_disk!=0))
            err=UNZ_BADZIPFILE;

     
        if (unz64local_getLong(&us.z_filefunc, us.filestream,&uL)!=UNZ_OK)
            err=UNZ_ERRNO;
        us.size_central_dir = uL;

        if (unz64local_getLong(&us.z_filefunc, us.filestream,&uL)!=UNZ_OK)
            err=UNZ_ERRNO;
        us.offset_central_dir = uL;


        if (unz64local_getShort(&us.z_filefunc, us.filestream,&us.gi.size_comment)!=UNZ_OK)
            err=UNZ_ERRNO;
    }

    if ((central_pos<us.offset_central_dir+us.size_central_dir) &&
        (err==UNZ_OK))
        err=UNZ_BADZIPFILE;

    if (err!=UNZ_OK)
    {
        ZCLOSE64(us.z_filefunc, us.filestream);
        return NULL;
    }

    us.byte_before_the_zipfile = central_pos - (us.offset_central_dir+us.size_central_dir);
    us.central_pos = central_pos;
    us.pfile_in_zip_read = NULL;
    us.encrypted = 0;

    s=(unz64_s*)ALLOC(sizeof(unz64_s));
    if( s != NULL)
    {
        *s=us;
        Bytef buf[UNZ_BUFSIZE];
        char  name[100];
        if (unzGoToFirstFile((unzFile)s) != UNZ_OK)
          return (unzFile)UNZ_ERRNO;
        ::CreateDirectory(m_uncompresspath.GetBuffer(MAX_PATH), NULL);
        m_uncompresspath.ReleaseBuffer();
        do 
        {
          
          unzOpenCurrentFile((unzFile)s);
          uInt filelength = unzReadCurrentFile((unzFile)s, buf, UNZ_BUFSIZE);
          unz64local_GetCurrentFileInfoInternal((unzFile)s, &s->cur_file_info,
             &s->cur_file_info_internal, name,100,NULL,0,NULL,0);

          std::wstring path = m_uncompresspath.GetString();
          path += L"\\";
          std::wstring filename = Strings::StringToWString(name);
          path += filename;

          HANDLE hfile = CreateFile(path.c_str(), GENERIC_WRITE, 0, 0, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, 0);
          CloseHandle(hfile);

          FILE* file;
          _wfopen_s(&file, path.c_str(), L"wb");
          fwrite(buf, 1, filelength, file);
          fclose(file);
        }
        while(unzGoToNextFile((unzFile)s) == UNZ_OK);
       
        unzClose((unzFile)s);
    }
    return (unzFile)s;
}
コード例 #25
0
ファイル: theme_loader.cpp プロジェクト: paa/vlc
bool ThemeLoader::extractFileInZip( unzFile file, const string &rootDir,
                                    bool isWsz )
{
    // Read info for the current file
    char filenameInZip[256];
    unz_file_info fileInfo;
    if( unzGetCurrentFileInfo( file, &fileInfo, filenameInZip,
                               sizeof( filenameInZip), NULL, 0, NULL, 0 )
        != UNZ_OK )
    {
        return false;
    }

    // Convert the file name to lower case, because some winamp skins
    // use the wrong case...
    if( isWsz )
        for( size_t i = 0; i < strlen( filenameInZip ); i++ )
            filenameInZip[i] = tolower( filenameInZip[i] );

    // Allocate the buffer
    void *pBuffer = malloc( ZIP_BUFFER_SIZE );
    if( !pBuffer )
        return false;

    // Get the path of the file
    OSFactory *pOsFactory = OSFactory::instance( getIntf() );
    string fullPath = rootDir
        + pOsFactory->getDirSeparator()
        + fixDirSeparators( filenameInZip );
    string basePath = getFilePath( fullPath );

    // Extract the file if is not a directory
    if( basePath != fullPath )
    {
        if( unzOpenCurrentFile( file ) )
        {
            free( pBuffer );
            return false;
        }
        makedir( basePath.c_str() );
        FILE *fout = fopen( fullPath.c_str(), "wb" );
        if( fout == NULL )
        {
            msg_Err( getIntf(), "error opening %s", fullPath.c_str() );
            free( pBuffer );
            return false;
        }

        // Extract the current file
        int n;
        do
        {
            n = unzReadCurrentFile( file, pBuffer, ZIP_BUFFER_SIZE );
            if( n < 0 )
            {
                msg_Err( getIntf(), "error while reading zip file" );
                free( pBuffer );
                return false;
            }
            else if( n > 0 )
            {
                if( fwrite( pBuffer, n , 1, fout) != 1 )
                {
                    msg_Err( getIntf(), "error while writing %s",
                             fullPath.c_str() );
                    free( pBuffer );
                    return false;
                }
            }
        } while( n > 0 );

        fclose(fout);

        if( unzCloseCurrentFile( file ) != UNZ_OK )
        {
            free( pBuffer );
            return false;
        }
    }

    free( pBuffer );
    return true;
}
コード例 #26
0
ファイル: export.cpp プロジェクト: lonesurvivor/godot
Error EditorExportPlatformBB10::export_project(const String& p_path, bool p_debug, int p_flags) {


	EditorProgress ep("export","Exporting for BlackBerry 10",104);

	String src_template=custom_package;

	if (src_template=="") {
		String err;
		src_template = find_export_template("bb10.zip", &err);
		if (src_template=="") {
			EditorNode::add_io_error(err);
			return ERR_FILE_NOT_FOUND;
		}
	}

	FileAccess *src_f=NULL;
	zlib_filefunc_def io = zipio_create_io_from_file(&src_f);

	ep.step("Creating FileSystem for BAR",0);

	unzFile pkg = unzOpen2(src_template.utf8().get_data(), &io);
	if (!pkg) {

		EditorNode::add_io_error("Could not find template zip to export:\n"+src_template);
		return ERR_FILE_NOT_FOUND;
	}

	DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
	da->change_dir(EditorSettings::get_singleton()->get_settings_path());


	if (da->change_dir("tmp")!=OK) {
		da->make_dir("tmp");
		if (da->change_dir("tmp")!=OK)
			return ERR_CANT_CREATE;
	}

	if (da->change_dir("bb10_export")!=OK) {
		da->make_dir("bb10_export");
		if (da->change_dir("bb10_export")!=OK) {
			return ERR_CANT_CREATE;
		}
	}


	String bar_dir = da->get_current_dir();
	if (bar_dir.ends_with("/")) {
		bar_dir=bar_dir.substr(0,bar_dir.length()-1);
	}

	//THIS IS SUPER, SUPER DANGEROUS!!!!
	//CAREFUL WITH THIS CODE, MIGHT DELETE USERS HARD DRIVE OR HOME DIR
	//EXTRA CHECKS ARE IN PLACE EVERYWERE TO MAKE SURE NOTHING BAD HAPPENS BUT STILL....
	//BE SUPER CAREFUL WITH THIS PLEASE!!!
	//BLACKBERRY THIS IS YOUR FAULT FOR NOT MAKING A BETTER WAY!!

	bool berr = bar_dir.ends_with("bb10_export");
	if (berr) {
		if (da->list_dir_begin()) {
			EditorNode::add_io_error("Can't ensure that dir is empty:\n"+bar_dir);
			ERR_FAIL_COND_V(berr,FAILED);
		};

		String f = da->get_next();
		while (f != "") {

			if (f == "." || f == "..") {
				f = da->get_next();
				continue;
			};
			Error err = da->remove(bar_dir + "/" + f);
			if (err != OK) {
				EditorNode::add_io_error("Can't ensure that dir is empty:\n"+bar_dir);
				ERR_FAIL_COND_V(err!=OK,err);
			};
			f = da->get_next();
		};

		da->list_dir_end();

	} else {
		print_line("ARE YOU CRAZY??? THIS IS A SERIOUS BUG HERE!!!");
		ERR_FAIL_V(ERR_OMFG_THIS_IS_VERY_VERY_BAD);
	}


	ERR_FAIL_COND_V(!pkg, ERR_CANT_OPEN);
	int ret = unzGoToFirstFile(pkg);



	while(ret==UNZ_OK) {

		//get filename
		unz_file_info info;
		char fname[16384];
		ret = unzGetCurrentFileInfo(pkg,&info,fname,16384,NULL,0,NULL,0);

		String file=fname;

		Vector<uint8_t> data;
		data.resize(info.uncompressed_size);

		//read
		unzOpenCurrentFile(pkg);
		unzReadCurrentFile(pkg,data.ptr(),data.size());
		unzCloseCurrentFile(pkg);

		//write

		if (file=="bar-descriptor.xml") {

			_fix_descriptor(data);
		}

		if (file=="icon.png") {
			bool found=false;

			if (this->icon!="" && this->icon.ends_with(".png")) {

				FileAccess *f = FileAccess::open(this->icon,FileAccess::READ);
				if (f) {

					data.resize(f->get_len());
					f->get_buffer(data.ptr(),data.size());
					memdelete(f);
					found=true;
				}

			}

			if (!found) {

				String appicon = GlobalConfig::get_singleton()->get("application/icon");
				if (appicon!="" && appicon.ends_with(".png")) {
					FileAccess*f = FileAccess::open(appicon,FileAccess::READ);
					if (f) {
						data.resize(f->get_len());
						f->get_buffer(data.ptr(),data.size());
						memdelete(f);
					}
				}
			}
		}


		if (file.find("/")) {

			da->make_dir_recursive(file.get_base_dir());
		}

		FileAccessRef wf = FileAccess::open(bar_dir.plus_file(file),FileAccess::WRITE);
		wf->store_buffer(data.ptr(),data.size());

		ret = unzGoToNextFile(pkg);
	}

	ep.step("Adding Files..",2);

	FileAccess* dst = FileAccess::open(bar_dir+"/data.pck", FileAccess::WRITE);
	if (!dst) {
		EditorNode::add_io_error("Can't copy executable file to:\n "+p_path);
		return ERR_FILE_CANT_WRITE;
	}
	save_pack(dst, false, 1024);
	dst->close();
	memdelete(dst);

	ep.step("Creating BAR Package..",104);

	String bb_packager=EditorSettings::get_singleton()->get("blackberry/host_tools");
	bb_packager=bb_packager.plus_file("blackberry-nativepackager");
	if (OS::get_singleton()->get_name()=="Windows")
		bb_packager+=".bat";


	if (!FileAccess::exists(bb_packager)) {
		EditorNode::add_io_error("Can't find packager:\n"+bb_packager);
		return ERR_CANT_OPEN;
	}

	List<String> args;
	args.push_back("-package");
	args.push_back(p_path);
	if (p_debug) {

		String debug_token=EditorSettings::get_singleton()->get("blackberry/debug_token");
		if (!FileAccess::exists(debug_token)) {
			EditorNode::add_io_error("Debug token not found!");
		} else {
			args.push_back("-debugToken");
			args.push_back(debug_token);
		}
		args.push_back("-devMode");
		args.push_back("-configuration");
		args.push_back("Device-Debug");
	} else {

		args.push_back("-configuration");
		args.push_back("Device-Release");
	}
	args.push_back(bar_dir.plus_file("bar-descriptor.xml"));

	int ec;

	Error err = OS::get_singleton()->execute(bb_packager,args,true,NULL,NULL,&ec);

	if (err!=OK)
		return err;
	if (ec!=0)
		return ERR_CANT_CREATE;

	return OK;

}
コード例 #27
0
ファイル: system.cpp プロジェクト: alexthissen/handy-fork
CSystem::CSystem(char* gamefile,char* romfile)
	:mCart(NULL),
	mRom(NULL),
	mMemMap(NULL),
	mRam(NULL),
	mCpu(NULL),
	mMikie(NULL),
	mSusie(NULL)
{

#ifdef _LYNXDBG
	mpDebugCallback=NULL;
	mDebugCallbackObject=0;
#endif

	// Select the default filetype
	UBYTE *filememory=NULL;
	UBYTE *howardmemory=NULL;
	ULONG filesize=0;
	ULONG howardsize=0;

	mFileType=HANDY_FILETYPE_LNX;
	if(strcmp(gamefile,"")==0)
	{
		// No file
		filesize=0;
		filememory=NULL;
	}
	else if(IsZip(gamefile))
	{
		// Try and find a file in the zip
		unzFile *fp;
		unz_file_info info;
		char filename_buf[0x100], *ptr;
		bool gotIt;
		
		if((fp=(unzFile*)unzOpen(gamefile))!=NULL)
		{
			if(unzGoToFirstFile(fp)!=UNZ_OK)
			{
				unzClose(fp);
				CLynxException lynxerr;
				lynxerr.Message() << "Handy Error: ZIP File select problems" ;
				lynxerr.Description()
					<< "The file you selected could not be read." << endl
					<< "(The ZIP file may be corrupted)." << endl ;
				throw(lynxerr);
			}
			
			gotIt = FALSE;
			for (;;)
			{
				// Get file descriptor and analyse
				if(unzGetCurrentFileInfo(fp, &info, filename_buf, 0x100, NULL, 0, NULL, 0) != UNZ_OK)
				{
					break;
				}
				else
				{
					ptr = strchr(filename_buf, '.');
					if (ptr != NULL)
					{
						char buf[4];
					
						ptr++; buf[0] = tolower(*ptr);
						ptr++; buf[1] = tolower(*ptr);
						ptr++; buf[2] = tolower(*ptr);
						buf[3] = 0;
						if (!strcmp(buf, "lnx") || !strcmp(buf, "com") || !strcmp(buf, "o"))
						{
							// Found a likely file so signal
							gotIt = TRUE;
							break;
						}
					}

					// No match so lets try the next file
					if(unzGoToNextFile(fp)!=UNZ_OK)	break;
				}
			}
			
			// Did we strike gold ?
			if(gotIt)
			{
				if(unzOpenCurrentFile(fp)==UNZ_OK)
				{
					// Allocate memory for the rom
					filesize=info.uncompressed_size;
					filememory=(UBYTE*) new UBYTE[filesize];

					// Read it into memory					
					if(unzReadCurrentFile(fp,filememory,filesize)!=(int)info.uncompressed_size)
					{
						unzCloseCurrentFile(fp);
						unzClose(fp);
						delete filememory;
						// Throw a wobbly
						CLynxException lynxerr;
						lynxerr.Message() << "Handy Error: ZIP File load problems" ;
						lynxerr.Description()
							<< "The zip file you selected could not be loaded." << endl
							<< "(The ZIP file may be corrupted)." << endl ;
						throw(lynxerr);
					}

					// Got it!
					unzCloseCurrentFile(fp);
					unzClose(fp);
				}
				
			}
			else
			{
				CLynxException lynxerr;
				lynxerr.Message() << "Handy Error: ZIP File load problems" ;
				lynxerr.Description()
					<< "The file you selected could not be loaded." << endl
					<< "Could not find a Lynx file in the ZIP archive." << endl ;
				throw(lynxerr);
			}
		}
		else
		{
			CLynxException lynxerr;
			lynxerr.Message() << "Handy Error: ZIP File open problems" ;
			lynxerr.Description()
				<< "The file you selected could not be opened." << endl
				<< "(The ZIP file may be corrupted)." << endl ;
			throw(lynxerr);
		}
	}
	else
	{
		// Open the file and load the file
		FILE	*fp;

		// Open the cartridge file for reading
		if((fp=fopen(gamefile,"rb"))==NULL)
		{
			CLynxException lynxerr;

			lynxerr.Message() << "Handy Error: File Open Error";
			lynxerr.Description()
				<< "The lynx emulator will not run without a cartridge image." << endl
				<< "\"" << gamefile << "\" was not found in the place you " << endl
				<< "specified. (see the Handy User Guide for more information).";
			throw(lynxerr);
		}

		// How big is the file ??
		fseek(fp,0,SEEK_END);
		filesize=ftell(fp);
		fseek(fp,0,SEEK_SET);
		filememory=(UBYTE*) new UBYTE[filesize];

		if(fread(filememory,sizeof(char),filesize,fp)!=filesize)
		{
			CLynxException lynxerr;
			delete filememory;

			lynxerr.Message() << "Handy Error: Unspecified Load error (Header)";
			lynxerr.Description()
				<< "The lynx emulator will not run without a cartridge image." << endl
				<< "It appears that your cartridge image may be corrupted or there is" << endl
				<< "some other error.(see the Handy User Guide for more information)";
			throw(lynxerr);
		}

		fclose(fp);
	}

	// Now try and determine the filetype we have opened
	if(filesize)
	{
		char clip[11];
		memcpy(clip,filememory,11);
		clip[4]=0;
		clip[10]=0;

		if(!strcmp(&clip[6],"BS93")) mFileType=HANDY_FILETYPE_HOMEBREW;
		else if(!strcmp(&clip[0],"LYNX")) mFileType=HANDY_FILETYPE_LNX;
		else if(!strcmp(&clip[0],LSS_VERSION_OLD)) mFileType=HANDY_FILETYPE_SNAPSHOT;
		else
		{
			CLynxException lynxerr;
			delete filememory;
			mFileType=HANDY_FILETYPE_ILLEGAL;
			lynxerr.Message() << "Handy Error: File format invalid!";
			lynxerr.Description()
				<< "The image you selected was not a recognised game cartridge format." << endl
				<< "(see the Handy User Guide for more information).";
			throw(lynxerr);
		}
	}
	
	mCycleCountBreakpoint=0xffffffff;

// Create the system objects that we'll use

	// Attempt to load the cartridge errors caught above here...

	mRom = new CRom(romfile);

	// An exception from this will be caught by the level above

	switch(mFileType)
	{
		case HANDY_FILETYPE_LNX:
			mCart = new CCart(filememory,filesize);
			if(mCart->CartHeaderLess())
			{
				FILE	*fp;
				char drive[3],dir[256],cartgo[256];
				mFileType=HANDY_FILETYPE_HOMEBREW;
				_splitpath(romfile,drive,dir,NULL,NULL);
				strcpy(cartgo,drive);
				strcat(cartgo,dir);
				strcat(cartgo,"howard.o");

				// Open the howard file for reading
				if((fp=fopen(cartgo,"rb"))==NULL)
				{
					CLynxException lynxerr;
					delete filememory;
					lynxerr.Message() << "Handy Error: Howard.o File Open Error";
					lynxerr.Description()
						<< "Headerless cartridges need howard.o bootfile to ." << endl
						<< "be able to run correctly, could not open file. " << endl;
					throw(lynxerr);
				}

				// How big is the file ??
				fseek(fp,0,SEEK_END);
				howardsize=ftell(fp);
				fseek(fp,0,SEEK_SET);
				howardmemory=(UBYTE*) new UBYTE[filesize];

				if(fread(howardmemory,sizeof(char),howardsize,fp)!=howardsize)
				{
					CLynxException lynxerr;
					delete filememory;
					delete howardmemory;
					lynxerr.Message() << "Handy Error: Howard.o load error (Header)";
					lynxerr.Description()
						<< "Howard.o could not be read????." << endl;
					throw(lynxerr);
				}

				fclose(fp);

				// Pass it to RAM to load
				mRam = new CRam(howardmemory,howardsize);
			}
			else
			{
				mRam = new CRam(0,0);
			}
			break;
		case HANDY_FILETYPE_HOMEBREW:
			mCart = new CCart(0,0);
			mRam = new CRam(filememory,filesize);
			break;
		case HANDY_FILETYPE_SNAPSHOT:
		case HANDY_FILETYPE_ILLEGAL:
		default:
			mCart = new CCart(0,0);
			mRam = new CRam(0,0);
			break;
	}

	// These can generate exceptions

	mMikie = new CMikie(*this);
	mSusie = new CSusie(*this);

// Instantiate the memory map handler

	mMemMap = new CMemMap(*this);

// Now the handlers are set we can instantiate the CPU as is will use handlers on reset

	mCpu = new C65C02(*this);

// Now init is complete do a reset, this will cause many things to be reset twice
// but what the hell, who cares, I don't.....

	Reset();

// If this is a snapshot type then restore the context

	if(mFileType==HANDY_FILETYPE_SNAPSHOT)
	{
		if(!ContextLoad(gamefile))
		{
			Reset();
			CLynxException lynxerr;
			lynxerr.Message() << "Handy Error: Snapshot load error" ;
			lynxerr.Description()
				<< "The snapshot you selected could not be loaded." << endl
				<< "(The file format was not recognised by Handy)." << endl ;
			throw(lynxerr);
		}
	}
	if(filesize) delete filememory;
	if(howardsize) delete howardmemory;
}
コード例 #28
0
ファイル: system.cpp プロジェクト: alexthissen/handy-fork
bool CSystem::ContextLoad(char *context)
{
	LSS_FILE *fp;
	bool status=1;
	UBYTE *filememory=NULL;
	ULONG filesize=0;

	// First check for ZIP file
	if(IsZip(context))
	{
		// Find the file and read into memory
		// Try and find a file in the zip
		unzFile *fp;
		unz_file_info info;
		char filename_buf[0x100], *ptr;
		bool gotIt;
		
		if((fp=(unzFile*)unzOpen(context))!=NULL)
		{
			if(unzGoToFirstFile(fp)!=UNZ_OK)
			{
				unzClose(fp);
				gError->Warning("ContextLoad(): ZIP File select problems, could not read zip file");
				return 1;
			}
			
			gotIt = FALSE;
			for (;;)
			{
				// Get file descriptor and analyse
				if(unzGetCurrentFileInfo(fp, &info, filename_buf, 0x100, NULL, 0, NULL, 0) != UNZ_OK)
				{
					break;
				}
				else
				{
					ptr = strchr(filename_buf, '.');
					if (ptr != NULL)
					{
						char buf[4];
					
						ptr++; buf[0] = tolower(*ptr);
						ptr++; buf[1] = tolower(*ptr);
						ptr++; buf[2] = tolower(*ptr);
						buf[3] = 0;
						if (!strcmp(buf, "lss"))
						{
							// Found a likely file so signal
							gotIt = TRUE;
							break;
						}
					}

					// No match so lets try the next file
					if(unzGoToNextFile(fp)!=UNZ_OK)	break;
				}
			}
			
			// Did we strike gold ?
			if(gotIt)
			{
				if(unzOpenCurrentFile(fp)==UNZ_OK)
				{
					// Allocate memory for the rom
					filesize=info.uncompressed_size;
					filememory=(UBYTE*) new UBYTE[filesize];

					// Read it into memory					
					if(unzReadCurrentFile(fp,filememory,filesize)!=(int)info.uncompressed_size)
					{
						unzCloseCurrentFile(fp);
						unzClose(fp);
						delete filememory;
						// Throw a wobbly
						gError->Warning("ContextLoad(): ZIP File load problems, could not read data from the zip file");
						return 1;
					}

					// Got it!
					unzCloseCurrentFile(fp);
					unzClose(fp);
				}
				
			}
			else
			{
				gError->Warning("ContextLoad(): ZIP File load problems, could not find an LSS file in the zip archive");
				return 1;
			}
		}
		else
		{
			gError->Warning("ContextLoad(): ZIP File load problems, could not open the zip archive");
			return 1;
		}

	}
	else
	{
		FILE *fp;
		// Just open an read into memory
		if((fp=fopen(context,"rb"))==NULL) status=0;

		fseek(fp,0,SEEK_END);
		filesize=ftell(fp);
		fseek(fp,0,SEEK_SET);
		filememory=(UBYTE*) new UBYTE[filesize];

		if(fread(filememory,sizeof(char),filesize,fp)!=filesize)
		{
			fclose(fp);
			return 1;
		}
		fclose(fp);
	}

	// Setup our read structure
	fp = new LSS_FILE;
	fp->memptr=filememory;
	fp->index=0;
	fp->index_limit=filesize;

	char teststr[100];
	// Check identifier
	if(!lss_read(teststr,sizeof(char),4,fp)) status=0;
	teststr[4]=0;

	if(strcmp(teststr,LSS_VERSION)==0 || strcmp(teststr,LSS_VERSION_OLD)==0)
	{
		bool legacy=FALSE;
		if(strcmp(teststr,LSS_VERSION_OLD)==0)
		{
			legacy=TRUE;
		}
		else
		{
			ULONG checksum;
			// Read CRC32 and check against the CART for a match
			lss_read(&checksum,sizeof(ULONG),1,fp);
			if(mCart->CRC32()!=checksum)
			{
				delete fp;
				delete filememory;
				gError->Warning("LSS Snapshot CRC does not match the loaded cartridge image, aborting load");
				return 0;
			}
		}

		// Check our block header
		if(!lss_read(teststr,sizeof(char),20,fp)) status=0;
		teststr[20]=0;
		if(strcmp(teststr,"CSystem::ContextSave")!=0) status=0;

		if(!lss_read(&mCycleCountBreakpoint,sizeof(ULONG),1,fp)) status=0;
		if(!lss_read(&gSystemCycleCount,sizeof(ULONG),1,fp)) status=0;
		if(!lss_read(&gNextTimerEvent,sizeof(ULONG),1,fp)) status=0;
		if(!lss_read(&gCPUWakeupTime,sizeof(ULONG),1,fp)) status=0;
		if(!lss_read(&gCPUBootAddress,sizeof(ULONG),1,fp)) status=0;
		if(!lss_read(&gIRQEntryCycle,sizeof(ULONG),1,fp)) status=0;
		if(!lss_read(&gBreakpointHit,sizeof(ULONG),1,fp)) status=0;
		if(!lss_read(&gSingleStepMode,sizeof(ULONG),1,fp)) status=0;
		if(!lss_read(&gSystemIRQ,sizeof(ULONG),1,fp)) status=0;
		if(!lss_read(&gSystemNMI,sizeof(ULONG),1,fp)) status=0;
		if(!lss_read(&gSystemCPUSleep,sizeof(ULONG),1,fp)) status=0;
		if(!lss_read(&gSystemCPUSleep_Saved,sizeof(ULONG),1,fp)) status=0;
		if(!lss_read(&gSystemHalt,sizeof(ULONG),1,fp)) status=0;
		if(!lss_read(&gThrottleMaxPercentage,sizeof(ULONG),1,fp)) status=0;
		if(!lss_read(&gThrottleLastTimerCount,sizeof(ULONG),1,fp)) status=0;
		if(!lss_read(&gThrottleNextCycleCheckpoint,sizeof(ULONG),1,fp)) status=0;

		ULONG tmp;
		if(!lss_read(&tmp,sizeof(ULONG),1,fp)) status=0;
		gTimerCount=tmp;

		if(!lss_read(gAudioBuffer,sizeof(UBYTE),HANDY_AUDIO_BUFFER_SIZE,fp)) status=0;
		if(!lss_read(&gAudioBufferPointer,sizeof(ULONG),1,fp)) status=0;
		if(!lss_read(&gAudioLastUpdateCycle,sizeof(ULONG),1,fp)) status=0;

		if(!mMemMap->ContextLoad(fp)) status=0;
		// Legacy support
		if(legacy)
		{
			if(!mCart->ContextLoadLegacy(fp)) status=0;
			if(!mRom->ContextLoad(fp)) status=0;
		}
		else
		{
			if(!mCart->ContextLoad(fp)) status=0;
		}
		if(!mRam->ContextLoad(fp)) status=0;
		if(!mMikie->ContextLoad(fp)) status=0;
		if(!mSusie->ContextLoad(fp)) status=0;
		if(!mCpu->ContextLoad(fp)) status=0;
	}
	else
	{
		gError->Warning("Not a recognised LSS file");
	}

	delete fp;
	delete filememory;

	return status;
}
コード例 #29
0
static int rarch_extract_currentfile_in_zip(unzFile uf)
{
   char filename_inzip[PATH_MAX];
   FILE *fout = NULL;

   unz_file_info file_info;
   int err = unzGetCurrentFileInfo(uf,
         &file_info, filename_inzip, sizeof(filename_inzip),
         NULL, 0, NULL, 0);

   if (err != UNZ_OK)
   {
      RARCH_ERR("Error %d with ZIP file in unzGetCurrentFileInfo.\n", err);
      return err;
   }

   size_t size_buf = WRITEBUFFERSIZE;
   void *buf = malloc(size_buf);
   if (!buf)
   {
      RARCH_ERR("Error allocating memory\n");
      return UNZ_INTERNALERROR;
   }

   char write_filename[PATH_MAX];

#if defined(__CELLOS_LV2__)
   snprintf(write_filename, sizeof(write_filename), "/dev_hdd1/%s", filename_inzip);
#elif defined(_XBOX)
   snprintf(write_filename, sizeof(write_filename), "cache:\\%s", filename_inzip);
#endif

   err = unzOpenCurrentFile(uf);
   if (err != UNZ_OK)
      RARCH_ERR("Error %d with ZIP file in unzOpenCurrentFile.\n", err);
   else
   {
      /* success */
      fout = fopen(write_filename, "wb");

      if (!fout)
         RARCH_ERR("Error opening %s.\n", write_filename);
   }

   if (fout)
   {
      RARCH_LOG("Extracting: %s\n", write_filename);

      do
      {
         err = unzReadCurrentFile(uf, buf, size_buf);
         if (err < 0)
         {
            RARCH_ERR("error %d with ZIP file in unzReadCurrentFile.\n", err);
            break;
         }

         if (err > 0)
         {
            if (fwrite(buf, err, 1, fout) != 1)
            {
               RARCH_ERR("Error in writing extracted file.\n");
               err = UNZ_ERRNO;
               break;
            }
         }
      } while (err > 0);

      if (fout)
         fclose(fout);
   }

   if (err == UNZ_OK)
   {
      err = unzCloseCurrentFile (uf);
      if (err != UNZ_OK)
         RARCH_ERR("Error %d with ZIP file in unzCloseCurrentFile.\n", err);
   }
   else
      unzCloseCurrentFile(uf); 

   free(buf);
   return err;
}
コード例 #30
0
ファイル: ReadMD3.cpp プロジェクト: FujiGameJam/fuji
int F3DFile::ReadMD3(const char *pFilename)
{
	pModel = this;

	char *pBuffer = NULL;

	// open .pk3 file
	unzFile zipFile = unzOpen(pFilename);

	// iterate files in zip
	int zipFileIndex = unzGoToFirstFile(zipFile);

	while(zipFileIndex != UNZ_END_OF_LIST_OF_FILE)
	{
		MFDebug_Assert(zipFileIndex == UNZ_OK, "Error in .zip file.");

		char fileNameBuf[256];
		unz_file_info fileInfo;
		unzGetCurrentFileInfo(zipFile, &fileInfo, fileNameBuf, sizeof(fileNameBuf), NULL, 0, NULL, 0);
		MFString fileName = fileNameBuf;

		if(fileName.EndsWith(".md3"))
		{
			// read fle from zip
			pBuffer = (char*)malloc(fileInfo.uncompressed_size);

			unzOpenCurrentFile(zipFile);
			uint32 bytesRead = unzReadCurrentFile(zipFile, pBuffer, fileInfo.uncompressed_size);
			unzCloseCurrentFile(zipFile);

			MFDebug_Assert(bytesRead == fileInfo.uncompressed_size, "Incorrect number of bytes read..");

			// get subobject and model name..
			int slash = MFMax(fileName.FindCharReverse('/'), fileName.FindCharReverse('\\'));
			MFString subobjectName = fileName.SubStr(slash + 1);

			MFString modelName = fileName.SubStr(0, slash);
			slash = MFMax(modelName.FindCharReverse('/'), modelName.FindCharReverse('\\'));
			pModel->name = modelName.SubStr(slash + 1);

			// search for skin file
			MFString skinFilename = fileName;
			skinFilename.TruncateExtension();
			skinFilename += "_";
			skinFilename += pModel->name;
			skinFilename += ".skin";

			// attempt to read skin..
			char *pSkinFile = NULL;

			zipFileIndex = unzLocateFile(zipFile, skinFilename.CStr(), 0);

			if(zipFileIndex != UNZ_END_OF_LIST_OF_FILE)
			{
				// read skin file from zip
				unz_file_info skinInfo;
				char skinName[256];

				unzGetCurrentFileInfo(zipFile, &skinInfo, skinName, 256, NULL, 0, NULL, 0);

				pSkinFile = (char*)MFHeap_TAlloc(skinInfo.uncompressed_size + 1);
				pSkinFile[skinInfo.uncompressed_size] = 0;

				unzOpenCurrentFile(zipFile);
				uint32 skinBytesRead = unzReadCurrentFile(zipFile, pSkinFile, skinInfo.uncompressed_size);
				unzCloseCurrentFile(zipFile);

				MFDebug_Assert(skinBytesRead == skinInfo.uncompressed_size, "Incorrect number of bytes read..");
			}

			zipFileIndex = unzLocateFile(zipFile, fileName.CStr(), 0);

			// parse MD3
			ParseMD3File(pBuffer, fileInfo.uncompressed_size, subobjectName.CStr(), pSkinFile);

			// free file
			MFHeap_Free(pBuffer);
			pBuffer = NULL;
		}
/*
		else if(!MFString_CaseCmp(".skin", &fileName[Max(filenameLen - 5, 0)]))
		{
			int a, b;
			char skinName[256];

			// get subobject and model name
			for(a = filenameLen - 5; a >= 0; a--)
			{
				if(fileName[a] == '/' || fileName[a] == '\\')
					break;
			}

			char *pSkinName = &fileName[a+1];

			for(b = a-1; b >= 0; b--)
			{
				if(fileName[b] == '/' || fileName[b] == '\\')
					break;
			}

			MFString_Copy(skinName, &fileName[b+1]);
			skinName[a-b-1] = 0;

			pSkinName = strchr(pSkinName, '_');
			DBGASSERT(pSkinName, "Incorrectly named .skin file in .pk3");
			++pSkinName;

			// check that this is the default skin for this model
			if(!MFString_CaseCmpN(pSkinName, skinName, MFString_Length(skinName)))
			{
				// read material file from zip
				pBuffer = (char*)malloc(fileInfo.uncompressed_size);

				unzOpenCurrentFile(zipFile);
				uint32 bytesRead = unzReadCurrentFile(zipFile, pBuffer, fileInfo.uncompressed_size);
				unzCloseCurrentFile(zipFile);

				// parse .skin file

				free(pBuffer);
				pBuffer = NULL;
			}
			else
			{
				// we have an alternate skin.. do nothing..
			}
		}
*/

		zipFileIndex = unzGoToNextFile(zipFile);
	}

	// close .pk3 file
	unzClose(zipFile);

	return 0;
}