Ejemplo n.º 1
0
// Save a whole buffer to disk
//QUE: Optimize size!!!!!!!!!!!!!!!!!!!!!!!
unsigned int j1FileSystem::Save(const char* file, const char* buffer, unsigned int size) const
{
	unsigned int ret = 0;
	//PHYSFS_addToSearchPath(file, 1);
	//PHYSFS_setWriteDir("Dev_class3_handout/Game/data_files.xml");

	PHYSFS_file* fs_file = PHYSFS_openWrite(file);

	if(fs_file != NULL)
	{
		PHYSFS_file* debug2 = PHYSFS_openWrite("data_files.xml");
		PHYSFS_sint64 written = PHYSFS_write(fs_file, (const void*)buffer, 1, size);
		if(written != size)
			LOG("File System error while writing to file %s: %s\n", file, PHYSFS_getLastError());
		else
			ret = (uint) written;

		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;
}
Ejemplo n.º 2
0
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;
}
Ejemplo n.º 3
0
static void writeSurfaces( 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_openWrite( outfile );
	if ( model )
	{
		PHYSFS_writeULE32( model, 0x090 );
		PHYSFS_writeULE32( model, surfaces.size() );
		for ( uint32_t i=0; i<surfaces.size(); i++ )
		{
			RenderSurface const &surf = surfaces[i];
			PHYSFS_writeCStr( model, surf.name.c_str() );
			PHYSFS_writeCStr( model, surf.mat->Name() );
			const ModelGeometry *geom = surf.geom;
			PHYSFS_writeSLE32( model, geom->m_numIndices );
			PHYSFS_writeSLE32( model, geom->m_numVerts );
			PHYSFS_write( model, geom->m_indices, sizeof(uint16_t)*geom->m_numIndices, 1 );
			PHYSFS_write( model, geom->m_verts, sizeof(geom->m_verts[0])*geom->m_numVerts, 1 );
		}
		PHYSFS_close( model );
	}
}
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;
}
Ejemplo n.º 5
0
fs_file fs_open(const char *path, const char *mode)
{
    fs_file fh;

    assert((mode[0] == 'r' && !mode[1]) ||
           (mode[0] == 'w' && (!mode[1] || mode[1] == '+')));

    if ((fh = malloc(sizeof (*fh))))
    {
        switch (mode[0])
        {
        case 'r':
            fh->handle = PHYSFS_openRead(path);
            break;

        case 'w':
            fh->handle = (mode[1] == '+' ?
                          PHYSFS_openAppend(path) :
                          PHYSFS_openWrite(path));
            break;
        }

        if (fh->handle)
        {
            PHYSFS_setBuffer(fh->handle, 0x2000);
        }
        else
        {
            free(fh);
            fh = NULL;
        }
    }

    return fh;
}
Ejemplo n.º 6
0
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;
}
Ejemplo n.º 7
0
bool NETstartLogging(void)
{
    time_t aclock;
    struct tm *newtime;
    char buf[256];
    static char filename[256] = {'\0'};
    int i;

    for (i = 0; i < NUM_GAME_PACKETS; i++)
    {
        packetcount[0][i] = 0;
        packetsize[0][i] = 0;
        packetcount[1][i] = 0;
        packetsize[1][i] = 0;
    }

    time( &aclock );                 /* Get time in seconds */
    newtime = localtime( &aclock );  /* Convert time to struct */

    snprintf(filename, sizeof(filename), "logs/netplay-%04d%02d%02d_%02d%02d%02d.log", newtime->tm_year + 1900, newtime->tm_mon + 1, newtime->tm_mday, newtime->tm_hour, newtime->tm_min, newtime->tm_sec);
    pFileHandle = PHYSFS_openWrite( filename ); // open the file
    if (!pFileHandle)
    {
        debug(LOG_ERROR, "Could not create net log %s: %s", filename,
              PHYSFS_getLastError());
        return false;
    }
    snprintf(buf, sizeof(buf), "NETPLAY log: %s\n", asctime(newtime));
    PHYSFS_write( pFileHandle, buf, strlen( buf ), 1 );
    return true;
}
Ejemplo n.º 8
0
void con_init(void)
{
	memset(con_buffer,0,sizeof(con_buffer));

	gamelog_fp = PHYSFS_openWrite("gamelog.txt");
	atexit(con_close);
}
Ejemplo n.º 9
0
FileStreamPtr ResourceManager::createFile(const std::string& fileName)
{
    PHYSFS_File* file = PHYSFS_openWrite(fileName.c_str());
    if(!file)
        stdext::throw_exception(stdext::format("failed to create file '%s': %s", fileName, PHYSFS_getLastError()));
    return FileStreamPtr(new FileStream(fileName, file, true));
}
Ejemplo n.º 10
0
void File::open(const std::string& filename, OpenMode mode, bool no_override)
{
	// check that we don't have anything opened!
	/// \todo maybe we could just close the old file here... but
	///		  then, this could also lead to errors...
	assert(mHandle == 0);

	// open depending on mode
	if( mode == OPEN_WRITE )
	{
		if(no_override && FileSystem::getSingleton().exists(filename))
		{
			BOOST_THROW_EXCEPTION(FileAlreadyExistsException(filename));
		}

		mHandle = PHYSFS_openWrite(filename.c_str());
	}
	 else
	{
		mHandle = PHYSFS_openRead(filename.c_str());
	}

	if (!mHandle)
	{
		BOOST_THROW_EXCEPTION(FileLoadException(filename));
	}

	mFileName = filename;
}
Ejemplo n.º 11
0
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());
   }
}
Ejemplo n.º 12
0
void
Downloader::download(const std::string& url, const std::string& filename)
{
  log_info << "download: " << url << " to " << filename << std::endl;
  std::unique_ptr<PHYSFS_file, int(*)(PHYSFS_File*)> fout(PHYSFS_openWrite(filename.c_str()),
                                                          PHYSFS_close);
  download(url, my_curl_physfs_write, fout.get());
}
Ejemplo n.º 13
0
ResourceWO * Resources::RetrieveWrite(PString & filename) {
    PHYSFS_file* file = PHYSFS_openWrite(filename);
    if(!file) {
        PError << "couldn't open file '" << filename << "' for writing: " << PHYSFS_getLastError() << endl;
        return NULL;
    };
    return new ResourceWO(file);
}
Ejemplo n.º 14
0
WriteFile* openWrite(const char* filename)
{
    PHYSFS_file* file = PHYSFS_openWrite(filename);
    if(!file)
        throw Exception("couldn't open file '%s' for writing: %s", filename,
                        PHYSFS_getLastError());

    return new WriteFile(file);
}
Ejemplo n.º 15
0
stream_t *file_open(const char *path, stream_mode_t mode, allocator_t *alloc)
{
  PHYSFS_File *file = NULL;
  stream_t *stream = NULL;
  char *pathcopy;
  size_t pathsize;

  if (!alloc)
    alloc = g_default_allocator;

  if (!path) {
    s_log_error("NULL path for file.");
    return NULL;
  }

  stream = stream_alloc(mode, alloc);

  if (stream) {
    switch (mode) {
      case STREAM_READ:
        file = PHYSFS_openRead(path);
      break;
      case STREAM_WRITE:
        file = PHYSFS_openWrite(path);
      break;
      case STREAM_APPEND:
        file = PHYSFS_openAppend(path);
      break;
      default: /* cannot reach */ break;
    }

    // if r+ failed because the file doesn't exist, open again with w
    if (file == NULL) {
      s_log_error("Failed to open file '%s' with mode %d. Error: %s.",
        path, mode, pfs_get_error());
      stream_close(stream);
      return NULL;
    }

    stream->read = file_read;
    stream->write = file_write;
    stream->seek = file_seek;
    stream->eof = file_eof;
    stream->close = file_close;

    // copy path string
    pathsize = strlen(path) + 1;
    pathcopy = com_malloc(alloc, pathsize);
    strncpy(pathcopy, path, pathsize);

    stream->context.pfs.file = file;
    stream->context.pfs.file_path = pathcopy;
  }

  return stream;
}
Ejemplo n.º 16
0
PHYSFS_File* openWithMode(char const * filename, mode openMode) {
	switch (openMode) {
	case WRITE:
		return PHYSFS_openWrite(filename);
	case APPEND:
		return PHYSFS_openAppend(filename);
	case READ:
		return PHYSFS_openRead(filename);
	}
}
Ejemplo n.º 17
0
void con_init(void)
{
	cxx_con_init();
	memset(con_buffer,0,sizeof(con_buffer));

	if (GameArg.DbgSafelog)
		gamelog_fp = PHYSFS_openWrite("gamelog.txt");
	else
		gamelog_fp = PHYSFSX_openWriteBuffered("gamelog.txt");
	atexit(con_close);
}
Ejemplo n.º 18
0
boost::shared_ptr<File> Filesystem::openWrite(const std::string &filename)
{
    PHYSFS_File *file_handle = PHYSFS_openWrite(filename.c_str());

    if (!file_handle) {
        throw_error;
    }

    boost::shared_ptr<File> file_ptr(new File(file_handle));
    return file_ptr;
}
Ejemplo n.º 19
0
bool TiXmlDocument::PHYSFS_SaveFile( const char * filename ) const
{
	std::stringstream s;
	toStream(s, 0);
	PHYSFS_file* f = PHYSFS_openWrite(filename);
	PHYSFS_sint64 length_write = PHYSFS_write(f, s.str().c_str(), 1, (PHYSFS_uint32) s.str().length());
	PHYSFS_close(f);
	if (length_write != s.str().length())
		return false;
	return true;
}
Ejemplo n.º 20
0
bool ResourceManager::saveFile(const std::string& fileName, const uchar* data, uint size)
{
    PHYSFS_file* file = PHYSFS_openWrite(fileName.c_str());
    if(!file) {
        g_logger.error(PHYSFS_getLastError());
        return false;
    }

    PHYSFS_write(file, (void*)data, size, 1);
    PHYSFS_close(file);
    return true;
}
Ejemplo n.º 21
0
 void TouchFile(std::string path) {
     if (!IsLoaded()) {
         Logger::begin("Filesystem", Logger::LogLevel_Error) << "FS not loaded" << Logger::end();
         return;
     }
     if (!hasSetUserDir) {
         Logger::begin("Filesystem", Logger::LogLevel_Error) << "UserDir needs to be set to touchFiles" << Logger::end();
         return;
     }
     PHYSFS_File* f = PHYSFS_openWrite(path.c_str());
     PHYSFS_close(f);
 }
OFileStreambuf::OFileStreambuf(const std::string& filename)
{
    file = PHYSFS_openWrite(filename.c_str());
    if(file == 0) {
        std::stringstream msg;
        msg << "Couldn't open file '" << filename << "': "
            << PHYSFS_getLastError();
        throw std::runtime_error(msg.str());
    }
    
    setp(buf, buf+sizeof(buf));
}
Ejemplo n.º 23
0
PHYSFS_File* vfs::openRaw(std::string const& name, VFile::OpenMode mode)
{
    PHYSFS_File* f;
    switch (mode) {
        case VFile::openR: f = PHYSFS_openRead(name.c_str()); break;
        case VFile::openW: f = PHYSFS_openWrite(name.c_str()); break;
        case VFile::openA: f = PHYSFS_openAppend(name.c_str()); break;
        default: throw Error("invalid openmode", false);
    }
    if (!f)
        throw Error("opening file \"" + name + "\" failed");
    return f;
}
Ejemplo n.º 24
0
void con_init(void)
{
	con_buffer = {};
	if (CGameArg.DbgSafelog)
		gamelog_fp.reset(PHYSFS_openWrite("gamelog.txt"));
	else
		gamelog_fp = PHYSFSX_openWriteBuffered("gamelog.txt");

	cli_init();
	cmd_init();
	cvar_init();

}
Ejemplo n.º 25
0
	bool copyDir(const char* dirSrcName, const char* dirDstName)
	{
		PHYSFS_Stat stat;
		if (PHYSFS_stat(dirSrcName, &stat) == 0 ||
			stat.filetype != PHYSFS_FILETYPE_DIRECTORY)
		{
			return false;
		}
		if (PHYSFS_stat(dirDstName, &stat) != 0 &&
			stat.filetype != PHYSFS_FILETYPE_DIRECTORY)
		{
			return false;
		}

		createDir(dirDstName);
		auto paths = PHYSFS_enumerateFiles(dirSrcName);
		if (paths != nullptr)
		{
			for (char** path = paths; *path != nullptr; path++)
			{
				auto fullSrcPath = std::string(dirSrcName) + '/' + *path;
				auto fullDstPath = std::string(dirDstName) + '/' + *path;

				if (PHYSFS_stat(fullSrcPath.c_str(), &stat) == 0)
				{
					continue;
				}
				if (stat.filetype == PHYSFS_FILETYPE_DIRECTORY)
				{
					copyDir(fullSrcPath.c_str(), fullDstPath.c_str());
				}
				else
				{
					// copy file (read source file and write destination)
					sf::PhysFSStream fileRead(fullSrcPath);
					auto fileWrite = PHYSFS_openWrite(fullDstPath.c_str());
					if (fileRead.hasError() == false &&
						fileWrite != nullptr)
					{
						std::vector<uint8_t> data((size_t)fileRead.getSize());
						fileRead.read(data.data(), fileRead.getSize());
						PHYSFS_writeBytes(fileWrite, data.data(), data.size());
						PHYSFS_close(fileWrite);
					}
				}
			}
			PHYSFS_freeList(paths);
			return true;
		}
		return false;
	}
Ejemplo n.º 26
0
//Open a file for writing, set up a buffer
PHYSFS_file *PHYSFSX_openWriteBuffered(const char *filename)
{
	PHYSFS_file *fp;
	PHYSFS_uint64 bufSize = 1024*1024;	// hmm, seems like an OK size.
	
	fp = PHYSFS_openWrite(filename);
	if (!fp)
		return NULL;
	
	while (!PHYSFS_setBuffer(fp, bufSize) && bufSize)
		bufSize /= 2;
	
	return fp;
}
Ejemplo n.º 27
0
Archivo: state.c Proyecto: btb/d2x
//	-----------------------------------------------------------------------------------
//	Imagine if C had a function to copy a file...
int copy_file(char *old_file, char *new_file)
{
	sbyte   *buf = NULL;
	int		buf_size;
	PHYSFS_file *in_file, *out_file;

	out_file = PHYSFS_openWrite(new_file);

	if (out_file == NULL)
		return -1;

	in_file = PHYSFS_openRead(old_file);

	if (in_file == NULL)
		return -2;

	buf_size = (int)PHYSFS_fileLength(in_file);
	while (buf_size && !(buf = d_malloc(buf_size)))
		buf_size /= 2;
	if (buf_size == 0)
		return -5;	// likely to be an empty file

	while (!PHYSFS_eof(in_file))
	{
		int bytes_read;

		bytes_read = (int)PHYSFS_read(in_file, buf, 1, buf_size);
		if (bytes_read < 0)
			Error("Cannot read from file <%s>: %s", old_file, PHYSFS_getLastError());

		Assert(bytes_read == buf_size || PHYSFS_eof(in_file));

		if (PHYSFS_write(out_file, buf, 1, bytes_read) < bytes_read)
			Error("Cannot write to file <%s>: %s", new_file, PHYSFS_getLastError());
	}

	d_free(buf);

	if (!PHYSFS_close(in_file))
	{
		PHYSFS_close(out_file);
		return -3;
	}

	if (!PHYSFS_close(out_file))
		return -4;

	return 0;
}
Ejemplo n.º 28
0
void iV_saveImage_JPEG(const char *fileName, const iV_Image *image)
{
	unsigned char *buffer = NULL;
	unsigned char *jpeg = NULL;
	char newfilename[PATH_MAX];
	unsigned int currentRow;
	const unsigned int row_stride = image->width * 3; // 3 bytes per pixel
	PHYSFS_file* fileHandle;
	unsigned char *jpeg_end;

	sstrcpy(newfilename, fileName);
	memcpy(newfilename + strlen(newfilename) - 4, ".jpg", 4);
	fileHandle = PHYSFS_openWrite(newfilename);
	if (fileHandle == NULL)
	{
		debug(LOG_ERROR, "pie_JPEGSaveFile: PHYSFS_openWrite failed (while opening file %s) with error: %s\n", fileName, PHYSFS_getLastError());
		return;
	}

	buffer = (unsigned char *)malloc(sizeof(const char*) * image->height * image->width);  // Suspect it should be sizeof(unsigned char)*3 == 3 here, not sizeof(const char *) == 8.
	if (buffer == NULL)
	{
		debug(LOG_ERROR, "pie_JPEGSaveFile: Couldn't allocate memory\n");
		return;
	}

	// Create an array of scanlines
	for (currentRow = 0; currentRow < image->height; ++currentRow)
	{
		// We're filling the scanline from the bottom up here,
		// otherwise we'd have a vertically mirrored image.
		memcpy(buffer + row_stride * currentRow, &image->bmp[row_stride * (image->height - currentRow - 1)], row_stride);
	}

	jpeg = (unsigned char *)malloc(sizeof(const char*) * image->height * image->width);  // Suspect it should be something else here, but sizeof(const char *) == 8 is hopefully big enough...
	if (jpeg == NULL)
	{
		debug(LOG_ERROR, "pie_JPEGSaveFile: Couldn't allocate memory\n");
		free(buffer);
		return;
	}

	jpeg_end = jpeg_encode_image(buffer, jpeg, 1, JPEG_FORMAT_RGB, image->width, image->height);
	PHYSFS_write(fileHandle, jpeg, jpeg_end - jpeg, 1);

	free(buffer);
	free(jpeg);
	PHYSFS_close(fileHandle);
}
Ejemplo n.º 29
0
 FilePtr File::Open(std::string path, FileMode mode) {
     PHYSFS_File* file = NULL;
     switch (mode) {
         case FileMode::Read:
             file = PHYSFS_openRead(path.c_str());
             break;
         case FileMode::Write:
             file = PHYSFS_openWrite(path.c_str());
             break;
         case FileMode::Append:
             file = PHYSFS_openAppend(path.c_str());
             break;
     }
     return new PhysFSFile(file, mode);
 }
Ejemplo n.º 30
0
 void WriteFile(std::string path, const char* content, long length) {
     if (!IsLoaded()) {
         Logger::begin("Filesystem", Logger::LogLevel_Error) << "FS not loaded" << Logger::end();
         return;
     }
     if (!hasSetUserDir) {
         Logger::begin("Filesystem", Logger::LogLevel_Error) << "UserDir needs to be set to writefiles" << Logger::end();
         return;
     }
     PHYSFS_File* f = PHYSFS_openWrite(path.c_str());
     if (!PHYSFS_write(f, content, sizeof(char), (unsigned int) length)) {
         Logger::begin("Filesystem", Logger::LogLevel_Error) << "File Write Failed" << Logger::end();
     }
     PHYSFS_close(f);
 }