bool j1Physfs::OpenFile(const char* file) { if (0 == PHYSFS_exists(file)) { return false; //file doesn't exist } PHYSFS_file* myfile = PHYSFS_openRead(file); // Get the lenght of the file file_lenght = PHYSFS_fileLength(myfile); // Get the file data. file_data = new Uint32[file_lenght]; int length_read = PHYSFS_read(myfile, file_data, 1, file_lenght); if (length_read != (int)file_lenght) { delete[] file_data; file_data = 0; return false; } PHYSFS_close(myfile); return true; }
File::File(const MountedFilePath& mountedFilePath, DataStream::OpenMode openMode) : impl(std::make_unique<File_Impl>()), mountedFilePath(mountedFilePath) { const char* path = mountedFilePath.path.c_str(); int fileExists = PHYSFS_exists(path); if (fileExists == 0) { throw Exception(std::string("File ") + path + " does not exist in the search path"); } switch (openMode) { case OpenMode::Read: impl->physfsFileHandle = PHYSFS_openRead(path); break; case OpenMode::Write: impl->physfsFileHandle = PHYSFS_openWrite(path); break; case OpenMode::Append: impl->physfsFileHandle = PHYSFS_openAppend(path); break; } if (impl->physfsFileHandle == nullptr) { throw Exception(std::string("Failed to open file ") + path + "\n" + PHYSFS_getLastError()); } }
static int seed_open(lua_State *L) // filename, mode -> physfs file { static const char * modes[] = { "rb", /*"wb", "ab",*/ NULL }; enum { READ /*, WRITE, APPEND*/ }; const char * filename = luaL_checkstring(L, 1); int mode = luaL_checkoption(L, 2, "rb", modes); PHYSFS_file * file; if(mode == READ) file = PHYSFS_openRead(filename); //else if(mode == WRITE) // file = PHYSFS_openWrite(filename); //else if(mode == APPEND) // file = PHYSFS_openAppend(filename); else assert(0); if(file) { *(PHYSFS_file **)lua_newuserdata(L, sizeof(file)) = file; luaL_getmetatable(L, "seed.file"); lua_setmetatable(L, -2); return 1; } else { lua_pushnil(L); lua_pushstring(L, PHYSFS_getLastError()); return 2; } }
static QImage loadQImage(char const *fileName, char const *format = nullptr) { PHYSFS_file *fileHandle = PHYSFS_openRead(fileName); if (fileHandle == nullptr) { return {}; } int64_t fileSizeGuess = PHYSFS_fileLength(fileHandle); // PHYSFS_fileLength may return -1. int64_t lengthRead = 0; std::vector<unsigned char> data(fileSizeGuess != -1? fileSizeGuess : 16384); while (true) { int64_t moreRead = PHYSFS_read(fileHandle, &data[lengthRead], 1, data.size() - lengthRead); lengthRead += std::max<int64_t>(moreRead, 0); if (lengthRead < data.size()) { PHYSFS_close(fileHandle); data.resize(lengthRead); QImage image; image.loadFromData(&data[0], data.size(), format); return std::move(image); } data.resize(data.size() + 16384); } }
bool FileManager::loadFile(const std::string & path, std::vector<u8>& out) { auto file = PHYSFS_openRead(path.c_str()); if (file == nullptr) { Log::write(Log::Error, fmt::format("Error: Unable to open file for reading. {}", path)); return false; } auto length = PHYSFS_fileLength(file); if (length == -1) { Log::write(Log::Error, fmt::format("Error: Unable to get file length. {}", path)); return false; } out.resize(length + 1); auto num = PHYSFS_read(file, out.data(), sizeof(out[0]), length); if (num < length / sizeof(out[0])) { Log::write(Log::Error, fmt::format("Error: Unable to read file contents. {}", path)); return false; } return true; }
static void fontSetEnumCB(void *data, const char *, const char *fname) { FontSetsCBData *d = static_cast<FontSetsCBData*>(data); FileSystemPrivate *p = d->p; /* Only consider filenames with font extensions */ const char *ext = p->findExt(fname); if (!ext) return; std::string lower(ext); strToLower(lower); if (!contains(p->extensions[FileSystem::Font], lower)) return; std::string filename("Fonts/"); filename += fname; PHYSFS_File *handle = PHYSFS_openRead(filename.c_str()); if (!handle) return; SDL_RWops ops; p->initReadOps(handle, ops, false); d->sfs->initFontSetCB(ops, filename); SDL_RWclose(&ops); }
Lux::Core::OpenedFile* Lux::Core::FileHandler::OpenFile(const String a_File, FileOpenMode a_OpenMode) { OpenedFile* retFile = nullptr; switch (a_OpenMode) { case Lux::Core::FileHandler::FILE_OPEN_READ: retFile = PHYSFS_openRead(a_File.c_str()); break; case Lux::Core::FileHandler::FILE_OPEN_WRITE: retFile = PHYSFS_openWrite(a_File.c_str()); break; case Lux::Core::FileHandler::FILE_OPEN_APPEND: retFile = PHYSFS_openAppend(a_File.c_str()); break; default: Utility::ThrowError("Unsupported file open mode."); break; } if (retFile == nullptr) { Utility::ThrowError("Could not open specified file: " + a_File + " . " + PHYSFS_getLastError()); } return retFile; }
natU8* FileManager::Read(const natChar* _filename, size_t* _size) { //#if defined(WINDOWS_TARGET) PHYSFS_file* file = PHYSFS_openRead(_filename); assert(file); *_size = PHYSFS_fileLength(file); assert(*_size != 0); natU8* buffer = new natU8[*_size]; PHYSFS_read(file, buffer, 1, static_cast<PHYSFS_uint32>(*_size)); PHYSFS_close(file); return buffer; /*#elif defined(EMSCRIPTEN_TARGET) std::ifstream file(_filename, std::ios::in|std::ios::binary|std::ios::ate); assert(file.is_open()); *_size = file.tellg(); assert(*_size != 0); natU8* buffer = new natU8[*_size]; file.seekg (0, std::ios::beg); file.read ((char*)buffer, *_size); file.close(); return buffer; #else #endif*/ }
const char* kp::file::read(const char* filename) { PHYSFS_File* handle = PHYSFS_openRead(filename); if(handle == NULL) { //kp::debug::error("PHYSFS_openRead(%s): %s", filename, PHYSFS_getLastError()); return NULL; } // Create a buffer big enough for the file PHYSFS_sint64 size = PHYSFS_fileLength(handle); // Append an extra byte to the string so we can null terminate it char* buffer = new char[size+1]; // Read the bytes if(PHYSFS_readBytes(handle, buffer, size) != size) { //kp::debug::error("PHYSFS_read: %s", PHYSFS_getLastError()); return NULL; } // Null terminate the buffer buffer[size] = '\0'; // Close the file handle PHYSFS_close(handle); return buffer; }
bool LoadImage( Image* image, const char* vfsPath ) { memset(image, 0, sizeof(Image)); PHYSFS_File* file = PHYSFS_openRead(vfsPath); if(!file) { Error("Can't load '%s': %s", vfsPath, PHYSFS_getLastError()); return false; } stbi_set_flip_vertically_on_load(1); image->data = stbi_load_from_callbacks(&PhysFSCallbacks, file, &image->width, &image->height, &image->channelCount, STBI_default); PHYSFS_close(file); if(!image->data) { Error("Can't load '%s': %s", vfsPath, stbi_failure_reason()); return false; } image->type = GL_UNSIGNED_BYTE; return true; }
//================================================== //! Load a file from the VFS into memory, can throw a FileIOException //================================================== void System::VFS::LoadRaw( const string& strFilename, vector<byte>& data ) { // Check to see if it exists if( !PHYSFS_exists(strFilename.c_str()) ) { THROW_EXCEPTION( FileReadException() << FileIOExceptionFilename(strFilename) ); } // Open the file shared_ptr<PHYSFS_file> pFile( PHYSFS_openRead(strFilename.c_str()), PHYSFS_close ); if( pFile.get() == NULL ) { THROW_EXCEPTION( FileReadException() << FileIOExceptionFilename(strFilename) ); } // Try to read the number of bytes, fail if we can't PHYSFS_sint64 nBytes= PHYSFS_fileLength( pFile.get() ); if( nBytes < 0 ) { THROW_EXCEPTION( FileReadException() << FileIOExceptionFilename(strFilename) ); } data.resize( unsigned(nBytes) ); // Try to read the data PHYSFS_sint64 nBytesRead= PHYSFS_read( pFile.get(), &data[0], sizeof(byte), data.size() ); // Check for unexpected length if( nBytesRead != nBytes ) { data.resize( unsigned(nBytesRead) ); THROW_EXCEPTION( FileReadException() << FileIOExceptionFilename(strFilename) ); } }
int FileSystem::load(const char* file, char **buffer) const { int ret = 0; PHYSFS_file *file_handle = PHYSFS_openRead(file); if (file_handle != NULL) { PHYSFS_sint64 size = PHYSFS_fileLength(file_handle); if (size > 0) { *buffer = new char[(int)size]; PHYSFS_sint64 bytes_readed = PHYSFS_read(file_handle, *buffer, 1, size); if (bytes_readed != size) { LOG("File system error while reading from file %s: %s", file, PHYSFS_getLastError()); RELEASE(buffer); } else ret = (int)size; } if (PHYSFS_close(file_handle) == 0) LOG("File %s is not closed properly. Error: %s", file, PHYSFS_getLastError()); } return ret; }
static int cmd_filelength(char *args) { PHYSFS_File *f; if (*args == '\"') { args++; args[strlen(args) - 1] = '\0'; } /* if */ f = PHYSFS_openRead(args); if (f == NULL) printf("failed to open. Reason: [%s].\n", PHYSFS_getLastError()); else { PHYSFS_sint64 len = PHYSFS_fileLength(f); if (len == -1) printf("failed to determine length. Reason: [%s].\n", PHYSFS_getLastError()); else printf(" (cast to int) %d bytes.\n", (int) len); PHYSFS_close(f); } /* else */ return(1); } /* cmd_filelength */
PHYSFS_File *openReadHandle(const char *filename, char *extBuf, size_t extBufN) { char found[512]; if (!completeFilename(filename, found, sizeof(found))) throw Exception(Exception::NoFileError, "%s", filename); PHYSFS_File *handle = PHYSFS_openRead(found); if (!handle) throw Exception(Exception::PHYSFSError, "PhysFS: %s", PHYSFS_getLastError()); if (!extBuf) return handle; for (char *q = found+strlen(found); q > found; --q) { if (*q == '/') break; if (*q != '.') continue; strcpySafe(extBuf, q+1, extBufN, -1); break; } return handle; }
void ResourceManager::loadFile(const std::string& fileName, std::iostream& out) { out.clear(std::ios::goodbit); if(m_hasSearchPath) { std::string fullPath = resolvePath(fileName); PHYSFS_file* file = PHYSFS_openRead(fullPath.c_str()); if(!file) { out.clear(std::ios::failbit); stdext::throw_exception(stdext::format("failed to load file '%s': %s", fullPath.c_str(), PHYSFS_getLastError())); } else { int fileSize = PHYSFS_fileLength(file); if(fileSize > 0) { std::vector<char> buffer(fileSize); PHYSFS_read(file, (void*)&buffer[0], 1, fileSize); out.write(&buffer[0], fileSize); } else out.clear(std::ios::eofbit); PHYSFS_close(file); out.seekg(0, std::ios::beg); } } else { std::ifstream fin(fileName); if(!fin) { out.clear(std::ios::failbit); stdext::throw_exception(stdext::format("failed to load file '%s': %s", fileName.c_str(), PHYSFS_getLastError())); } else { out << fin.rdbuf(); } } }
// Read a whole file and put it in a new buffer unsigned int j1FileSystem::Load(const char* file, char** buffer) const { unsigned int ret = 0; PHYSFS_file* fs_file = PHYSFS_openRead(file); if(fs_file != NULL) { PHYSFS_sint32 size = PHYSFS_fileLength(fs_file); if(size > 0) { *buffer = new char[size]; int readed = PHYSFS_read(fs_file, *buffer, 1, size); if(readed != size) { LOG("File System error while reading from file %s: %s\n", file, PHYSFS_getLastError()); RELEASE(buffer); } else ret = readed; } if(PHYSFS_close(fs_file) == 0) LOG("File System error while closing file %s: %s\n", file, PHYSFS_getLastError()); } else LOG("File System error while opening file %s: %s\n", file, PHYSFS_getLastError()); return ret; }
SDL_RWops* get_physfs_SDLRWops(const std::string& filename) { // check this as PHYSFS seems to be buggy and still returns a // valid pointer in this case if(filename.empty()) { throw std::runtime_error("Couldn't open file: empty filename"); } PHYSFS_file* file = (PHYSFS_file*) PHYSFS_openRead(filename.c_str()); if(!file) { std::stringstream msg; msg << "Couldn't open '" << filename << "': " << PHYSFS_getLastError(); throw std::runtime_error(msg.str()); } SDL_RWops* ops = new SDL_RWops(); ops->type = 0; ops->hidden.unknown.data1 = file; ops->seek = funcSeek; ops->read = funcRead; ops->write = 0; ops->close = funcClose; return ops; }
void SetWindowIcon(photon_window &window, const std::string &filename){ if(PHYSFS_exists(filename.c_str())){ auto fp = PHYSFS_openRead(filename.c_str()); intmax_t length = PHYSFS_fileLength(fp); if(length > 0){ uint8_t *buffer = new uint8_t[length]; PHYSFS_read(fp, buffer, 1, length); PHYSFS_close(fp); SDL_RWops *rw = SDL_RWFromMem(buffer, length); SDL_Surface *icon = IMG_Load_RW(rw, 1); if(icon == nullptr){ PrintToLog("ERROR: icon loading failed! %s", IMG_GetError()); } SDL_SetWindowIcon(window.window_SDL, icon); SDL_FreeSurface(icon); delete[] buffer; }else{ PrintToLog("ERROR: Unable to open image file \"%s\"!"); } }else{ PrintToLog("ERROR: Image file \"%s\" does not exist!", filename.c_str()); } }
/* Load an audio file */ static bool dataAudioCfgLoad(const char* fileName, void **ppData) { bool success; PHYSFS_file* fileHandle; *ppData = NULL; if (audio_Disabled()) { return true; } debug(LOG_WZ, "Reading...[directory: %s] %s", PHYSFS_getRealDir(fileName), fileName); fileHandle = PHYSFS_openRead(fileName); if (fileHandle == NULL) { return false; } success = ParseResourceFile(fileHandle); PHYSFS_close(fileHandle); return success; }
static bool readSurfaces( const char *filename, std::vector< RenderSurface > &surfaces ) { uint64_t hashedName = HashedString( 0, filename ); char outfile[256]; PHYSFS_mkdir( "static_models/" ); sprintf( outfile, "static_models/%08x_%08x.sm", (uint32_t)(hashedName>>32), (uint32_t)(hashedName&0xffffffff) ); PHYSFS_File *model = PHYSFS_openRead( outfile ); if ( model ) { unsigned int ver, numSurf; PHYSFS_readULE32( model, &ver ); PHYSFS_readULE32( model, &numSurf ); surfaces.resize( numSurf ); for ( uint32_t i=0; i<surfaces.size(); i++ ) { RenderSurface &surf = surfaces[i]; PHYSFS_readCStr( model, surf.name ); std::string mat; PHYSFS_readCStr( model, mat ); surf.mat = materialManager()->Load( mat.c_str() ); ModelGeometry *geom = new ModelGeometry; surf.geom = geom; PHYSFS_readSLE32( model, &geom->m_numIndices ); PHYSFS_readSLE32( model, &geom->m_numVerts ); geom->m_indices = new unsigned short[geom->m_numIndices]; geom->m_verts = new ModelVert[geom->m_numVerts]; PHYSFS_read( model, geom->m_indices, sizeof(uint16_t)*geom->m_numIndices, 1 ); PHYSFS_read( model, geom->m_verts, sizeof(geom->m_verts[0])*geom->m_numVerts, 1 ); } PHYSFS_close( model ); return true; } return false; }
//Open a file for reading, set up a buffer PHYSFS_file *PHYSFSX_openReadBuffered(const char *filename) { PHYSFS_file *fp; PHYSFS_uint64 bufSize; char filename2[PATH_MAX]; if (filename[0] == '\x01') { //FIXME: don't look in dir, only in hogfile filename++; } snprintf(filename2, sizeof(filename2), "%s", filename); PHYSFSEXT_locateCorrectCase(filename2); fp = PHYSFS_openRead(filename2); if (!fp) return NULL; bufSize = PHYSFS_fileLength(fp); while (!PHYSFS_setBuffer(fp, bufSize) && bufSize) bufSize /= 2; // even if the error isn't memory full, for a 20MB file it'll only do this 8 times return fp; }
SoundFile* load_sound_file(const std::string& filename) { if(filename.length() > 6 && filename.compare(filename.length()-6, 6, ".music") == 0) { return load_music_file(filename); } PHYSFS_file* file = PHYSFS_openRead(filename.c_str()); if(!file) { std::stringstream msg; msg << "Couldn't open '" << filename << "': " << PHYSFS_getLastError(); throw std::runtime_error(msg.str()); } try { char magic[4]; if(PHYSFS_read(file, magic, sizeof(magic), 1) != 1) throw std::runtime_error("Couldn't read magic, file too short"); PHYSFS_seek(file, 0); if(strncmp(magic, "RIFF", 4) == 0) return new WavSoundFile(file); else if(strncmp(magic, "OggS", 4) == 0) return new OggSoundFile(file, 0, -1); else throw std::runtime_error("Unknown file format"); } catch(std::exception& e) { std::stringstream msg; msg << "Couldn't read '" << filename << "': " << e.what(); throw std::runtime_error(msg.str()); } }
/** Plays the given audio file as a stream and reports back when it has finished * playing. * \param fileName the (OggVorbis) file to play from * \param volume the volume to use while playing this file (in the range of * 0.0 - 1.0) * \param onFinished a callback function to invoke when playing of this stream * has been finished. You can use NULL to specifiy no callback function. * \param user_data a pointer to contain some user data to pass along to the * finished callback. * \return a pointer to the currently playing stream when the stream is playing * (and as such the callback will be invoked some time in the future), * NULL when the stream didn't start playing (and the callback won't be * invoked). * \note The returned pointer will become invalid/dangling immediately after * the \c onFinished callback is invoked. * \note You must _never_ manually free() the memory used by the returned * pointer. */ AUDIO_STREAM* audio_PlayStream(const char* fileName, float volume, void (*onFinished)(void*), void* user_data) { PHYSFS_file* fileHandle; AUDIO_STREAM* stream; // If audio is not enabled return false to indicate that the given callback // will not be invoked. if (g_bAudioEnabled == false) { return NULL; } // Open up the file fileHandle = PHYSFS_openRead(fileName); debug(LOG_WZ, "Reading...[directory: %s] %s", PHYSFS_getRealDir(fileName), fileName); if (fileHandle == NULL) { debug(LOG_ERROR, "sound_LoadTrackFromFile: PHYSFS_openRead(\"%s\") failed with error: %s\n", fileName, PHYSFS_getLastError()); return NULL; } stream = sound_PlayStream(fileHandle, volume, onFinished, user_data); if (stream == NULL) { PHYSFS_close(fileHandle); return NULL; } return stream; }
SoundFile* load_music_file(const std::string& filename) { lisp::Parser parser(false); const lisp::Lisp* root = parser.parse(filename); const lisp::Lisp* music = root->get_lisp("tuxjunior-music"); if(music == NULL) throw std::runtime_error("file is not a tuxjunior-music file."); std::string raw_music_file; float loop_begin = 0; float loop_at = -1; music->get("file", raw_music_file); music->get("loop-begin", loop_begin); music->get("loop-at", loop_at); if(loop_begin < 0) { throw std::runtime_error("can't loop from negative value"); } std::string basedir = FileSystem::dirname(filename); raw_music_file = FileSystem::normalize(basedir + raw_music_file); PHYSFS_file* file = PHYSFS_openRead(raw_music_file.c_str()); if(!file) { std::stringstream msg; msg << "Couldn't open '" << raw_music_file << "': " << PHYSFS_getLastError(); throw std::runtime_error(msg.str()); } return new OggSoundFile(file, loop_begin, loop_at); }
static void *file_phys_fopen(const char *filename, const char *mode) { PHYSFS_file *phys; ALLEGRO_FILE_PHYSFS *fp; /* XXX handle '+' modes */ /* It might be worth adding a function to parse mode strings, to be * shared amongst these kinds of addons. */ if (streq(mode, "r") || streq(mode, "rb")) phys = PHYSFS_openRead(filename); else if (streq(mode, "w") || streq(mode, "wb")) phys = PHYSFS_openWrite(filename); else if (streq(mode, "a") || streq(mode, "ab")) phys = PHYSFS_openAppend(filename); else phys = NULL; if (!phys) { phys_set_errno(NULL); return NULL; } fp = al_malloc(sizeof(*fp)); if (!fp) { al_set_errno(ENOMEM); PHYSFS_close(phys); return NULL; } fp->phys = phys; fp->error_indicator = false; return fp; }
bool ResourceManager::copyFile(const std::string &src, const std::string &dst) { PHYSFS_file *srcFile = PHYSFS_openRead(src.c_str()); if (!srcFile) { logger->log("Read error: %s", PHYSFS_getLastError()); return false; } PHYSFS_file *dstFile = PHYSFS_openWrite(dst.c_str()); if (!dstFile) { logger->log("Write error: %s", PHYSFS_getLastError()); PHYSFS_close(srcFile); return false; } int fileSize = PHYSFS_fileLength(srcFile); void *buf = malloc(fileSize); PHYSFS_read(srcFile, buf, 1, fileSize); PHYSFS_write(dstFile, buf, 1, fileSize); PHYSFS_close(srcFile); PHYSFS_close(dstFile); free(buf); return true; }
void *ResourceManager::loadFile(const std::string &fileName, int &fileSize) { // Attempt to open the specified file using PhysicsFS PHYSFS_file *file = PHYSFS_openRead(fileName.c_str()); // If the handler is an invalid pointer indicate failure if (file == NULL) { logger->log("Warning: Failed to load %s: %s", fileName.c_str(), PHYSFS_getLastError()); return NULL; } // Log the real dir of the file logger->log("Loaded %s/%s", PHYSFS_getRealDir(fileName.c_str()), fileName.c_str()); // Get the size of the file fileSize = PHYSFS_fileLength(file); // Allocate memory and load the file void *buffer = malloc(fileSize); PHYSFS_read(file, buffer, 1, fileSize); // Close the file and let the user deallocate the memory PHYSFS_close(file); return buffer; }
bool physfsFile::prepareRead() { PHYSFS_uint64 pos = PHYSFS_tell(fhandle); PHYSFS_close(fhandle); fhandle = PHYSFS_openRead(pname); PHYSFS_seek(fhandle, pos); //LOG_MSG("Goto read (%s at %i)",pname,PHYSFS_tell(fhandle)); return true; }
DataStream::DataStream(const Ogre::String& name, const Ogre::String& filename) : Ogre::DataStream(name) { LOG_FUNCTION file = PHYSFS_openRead(filename.c_str()); if (!file) throw Exception(PHYSFS_getLastError()); mSize = (size_t) PHYSFS_fileLength(file); }
FileStreamPtr ResourceManager::openFile(const std::string& fileName) { std::string fullPath = resolvePath(fileName); PHYSFS_File* file = PHYSFS_openRead(fullPath.c_str()); if(!file) stdext::throw_exception(stdext::format("unable to open file '%s': %s", fullPath, PHYSFS_getLastError())); return FileStreamPtr(new FileStream(fullPath, file, false)); }