int StaticFileCacheData::tryCreateGziped()
{
    if ( !s_iAutoUpdateStaticGzip )
        return -1;
    off_t size = m_fileData.getFileSize();
    if (( size > s_iMaxFileSize )||( size < s_iMinFileSize ))
        return -1;
    char *p = m_gzippedPath.buf() + m_gzippedPath.len() + 4;
    int fd = createLockFile( m_gzippedPath.buf(), p );
    if ( fd == -1 )
        return -1;
    close( fd );
    if ( size < 409600 )
    {

        long ret = compressFile();
        *p = 'l';
        unlink( m_gzippedPath.buf() );
        *p = 0;
        return ret;

    }
    else
    {
        //IMPROVE: move this to a standalone process,
        //          fork() is too expensive.

        if ( D_ENABLED( DL_MORE ))
        {
            LOG_D(( "To compressed file %s in another process.",
                    m_real.c_str() ));
        }
        int forkResult;
        forkResult = fork();
        if( forkResult )  //error or parent process
        {
            return -1;
        }
        //child process
        setpriority( PRIO_PROCESS, 0, 5 );

        long ret = compressFile();
        if ( ret == -1 )
        {
            LOG_WARN(( "Failed to compress file %s!", m_real.c_str() ));

        }
        *p = 'l';
        unlink( m_gzippedPath.buf() );
        *p = 0;
        exit(1);
    }
}
Esempio n. 2
0
int main(int argc, char* argv[])
{
	if (argc == ARG_NUM) {
		char* originalFileName = argv[1];

if (isTextFile(originalFileName)) {
	char* compressedFileName = compressFile(originalFileName);
	if (compressedFileName != NULL) {
		compareFileSize(originalFileName, compressedFileName);

		char* decompressedFileName = decompressFile(compressedFileName);
		if (decompressedFileName != NULL) {
			compareFileSize(compressedFileName, decompressedFileName);
		}
	}
}
else {
	printUsage();
}
	}
	else {
		printUsage();
	}

	system("pause");
	return 0;
}
Esempio n. 3
0
int main(int argc, char *argv[]) {
FILE *input;
BIT_FILE *output;

if (argc < 3)
  {
    fprintf(stderr, "Usage: compress <input file> <output file>\n");
    exit(1);
  }

fprintf(stderr, "Compressing file %s\n", argv[1]);

 if ((input = fopen(argv[1], "r")) == NULL) 
   error("Opening input file");
 
 if ( (output = openBitFile(argv[2], "w")) == NULL) 
   error("Opening output bit file");
 
fprintf(stderr, "Calling your function\n");


// Calls your function in the file "compress.c"
 compressFile(input,output);

 
 closeBitFile(output);
 if ( fclose(input) )
   error("Closing Input File");;

fprintf(stderr, "Compressed file: %s\n", argv[2]);
}
Esempio n. 4
0
/**OK
 * Comprime il file fileName nel file fileCompressed.
 * Se la funzione fallisce restituisce false e cancella il file che si e tentato
 * di creare.
 *
 * La funzione fallisce se:
 * * non si riesce ad aprire l'oggetto zip;
 * * la compressione del file fallisce;
 * * non si riesce a chiudere l'oggetto zip;
 */
bool JlCompress::compressFile(QString fileCompressed, QString file) {
    // Creo lo zip
    QuaZip* zip  = new QuaZip(QFileInfo(fileCompressed).absoluteFilePath());
    QDir().mkpath(QFileInfo(fileCompressed).absolutePath());
    if(!zip->open(QuaZip::mdCreate)) {
        delete zip;
        QFile::remove(fileCompressed);
        return false;
    }

    // Aggiungo il file
    if (!compressFile(zip,file,QFileInfo(file).fileName())) {
        delete zip;
        QFile::remove(fileCompressed);
        return false;
    }

    // Chiudo il file zip
    zip->close();
    if(zip->getZipError()!=0) {
        delete zip;
        QFile::remove(fileCompressed);
        return false;
    }
    delete zip;

    return true;
}
Esempio n. 5
0
int main(){
    Node *tree;
    int codeTable[27], codeTable2[27];
    int compress;
    char filename[20];
    FILE *input, *output;

    buildHuffmanTree(&tree);

    fillTable(codeTable, tree, 0);

    invertCodes(codeTable,codeTable2);

    /*get input details from user*/
    printf("Type the name of the file to process:\n");
    scanf("%s",filename);
    printf("Type 1 to compress and 2 to decompress:\n");
    scanf("%d",&compress);

    input = fopen(filename, "r");
    output = fopen("output.txt","w");

    if (compress==1)
        compressFile(input,output,codeTable2);
    else
        decompressFile(input,output, tree);

    return 0;
}
Esempio n. 6
0
bool FstReader::addTextures(const QFileInfo& texdir) {
    QStringList filter;
    filter << "*.png" << "*.tif" << "*.jpg" << "*.jpeg";
    
    QFileInfoList list = QDir(texdir.filePath()).entryInfoList(filter,
                                                               QDir::Files |
                                                               QDir::AllDirs |
                                                               QDir::NoDotAndDotDot |
                                                               QDir::NoSymLinks);
    foreach (QFileInfo info, list) {
        if (info.isFile()) {
            // Compress and copy
            if (!compressFile(info.filePath(), _zipDir.path() + "/" + info.fileName())) {
                return false;
            }
            _totalSize += info.size();
            if (!addPart(_zipDir.path() + "/" + info.fileName(),
                         QString("texture%1").arg(++_texturesCount))) {
                return false;
            }
        } else if (info.isDir()) {
            if (!addTextures(info)) {
                return false;
            }
        } else {
            qDebug() << "[DEBUG] Invalid file type : " << info.filePath();
        }
    }
    
    return true;
}
Esempio n. 7
0
/**OK
 * Comprime la cartella dir nel file fileCompressed, se recursive e true allora
 * comprime anche le sotto cartelle. I nomi dei file preceduti dal path creato
 * togliendo il pat della cartella origDir al path della cartella dir.
 * Se la funzione fallisce restituisce false e cancella il file che si e tentato
 * di creare.
 *
 * La funzione fallisce se:
 * * zip==NULL;
 * * l'oggetto zip e stato aperto in una modalita non compatibile con l'aggiunta di file;
 * * la cartella dir non esiste;
 * * la compressione di una sotto cartella fallisce (1);
 * * la compressione di un file fallisce;
 * (1) La funzione si richiama in maniera ricorsiva per comprimere le sotto cartelle
 * dunque gli errori di compressione di una sotto cartella sono gli stessi di questa
 * funzione.
 */
bool JlCompress::compressSubDir(QuaZip* zip, QString dir, QString origDir, const int LEVEL, bool recursive) {
    // zip: oggetto dove aggiungere il file
    // dir: cartella reale corrente
    // origDir: cartella reale originale
    // (path(dir)-path(origDir)) = path interno all'oggetto zip

    // Controllo l'apertura dello zip
    if (!zip) return false;
    if (zip->getMode()!=QuaZip::mdCreate &&
        zip->getMode()!=QuaZip::mdAppend &&
        zip->getMode()!=QuaZip::mdAdd) return false;

    // Controllo la cartella
    QDir directory(dir);
    if (!directory.exists()) return false;

    QDir origDirectory(origDir);
	if (dir != origDir) {
		QuaZipFile dirZipFile(zip);
        const int METHOD = LEVEL != 0 ? Z_DEFLATED : Z_BINARY;
        if (!dirZipFile.open(QIODevice::WriteOnly,
            QuaZipNewInfo(origDirectory.relativeFilePath(dir) + "/", dir), NULL, 0, METHOD, LEVEL)) {
				return false;
		}
		dirZipFile.close();
	}


    // Se comprimo anche le sotto cartelle
    if (recursive) {
        // Per ogni sotto cartella
        QFileInfoList files = directory.entryInfoList(QDir::AllDirs|QDir::NoDotAndDotDot);
        Q_FOREACH (QFileInfo file, files) {
            // Comprimo la sotto cartella
            if(!compressSubDir(zip,file.absoluteFilePath(),origDir,LEVEL,recursive)) return false;
        }
    }

    // Per ogni file nella cartella
    QFileInfoList files = directory.entryInfoList(QDir::Files);
    Q_FOREACH (QFileInfo file, files) {
        // Se non e un file o e il file compresso che sto creando
        if(!file.isFile()||file.absoluteFilePath()==zip->getZipName()) continue;

        // Creo il nome relativo da usare all'interno del file compresso
        QString filename = origDirectory.relativeFilePath(file.absoluteFilePath());

        // Comprimo il file
        if (!compressFile(zip,file.absoluteFilePath(),filename,LEVEL)) return false;
    }

    return true;
}
 // компрессуем
void compress(const char *inpFileName, const char *lz4FileName)
{
    
    FILE* inpFp = fopen(inpFileName, "rb");
    FILE* outFp = fopen(lz4FileName, "wb");

    printf("compress : %s -> %s\n", inpFileName, lz4FileName);
    compressFile(outFp, inpFp);
    printf("compress : done\n");
    fclose(inpFp);
    fclose(outFp);

}
Esempio n. 9
0
int main()
{
  
   char outFileName[PATH_MAX] = { 0 };
   FILE *fp = fopen(__FILE__, "r");
   if (fp)
     {
        sprintf(outFileName, "%s.gz", __FILE__);
        if (compressFile(fp, outFileName) != 0)
          {
             fclose(fp);
             return -1;
          }
        fclose(fp);
     }
   return 0;
}
Esempio n. 10
0
/**OK
 * Comprime i file specificati in files nel file fileCompressed.
 * Se la funzione fallisce restituisce false e cancella il file che si e tentato
 * di creare.
 *
 * La funzione fallisce se:
 * * non si riesce ad aprire l'oggetto zip;
 * * la compressione di un file fallisce;
 * * non si riesce a chiudere l'oggetto zip;
 */
bool JlCompress::compressFiles(QString fileCompressed, QStringList files) {
    // Creo lo zip
    QuaZip zip(fileCompressed);
    QDir().mkpath(QFileInfo(fileCompressed).absolutePath());
    if(!zip.open(QuaZip::mdCreate)) {
        QFile::remove(fileCompressed);
        return false;
    }

    // Comprimo i file
    QFileInfo info;
    Q_FOREACH (QString file, files) {
        info.setFile(file);
        if (!info.exists() || !compressFile(&zip,file,info.fileName())) {
            QFile::remove(fileCompressed);
            return false;
        }
    }
Esempio n. 11
0
/**OK
 * Comprime la cartella dir nel file fileCompressed, se recursive e true allora
 * comprime anche le sotto cartelle. I nomi dei file preceduti dal path creato
 * togliendo il pat della cartella origDir al path della cartella dir.
 * Se la funzione fallisce restituisce false e cancella il file che si e tentato
 * di creare.
 *
 * La funzione fallisce se:
 * * zip==NULL;
 * * l'oggetto zip e stato aperto in una modalita non compatibile con l'aggiunta di file;
 * * la cartella dir non esiste;
 * * la compressione di una sotto cartella fallisce (1);
 * * la compressione di un file fallisce;
 * (1) La funzione si richiama in maniera ricorsiva per comprimere le sotto cartelle
 * dunque gli errori di compressione di una sotto cartella sono gli stessi di questa
 * funzione.
 */
bool JlCompress::compressSubDir(QuaZip* zip, QString dir, QString origDir, bool recursive) {
    // zip: oggetto dove aggiungere il file
    // dir: cartella reale corrente
    // origDir: cartella reale originale
    // (path(dir)-path(origDir)) = path interno all'oggetto zip

    // Controllo l'apertura dello zip
    if (!zip) return false;
    if (zip->getMode()!=QuaZip::mdCreate &&
        zip->getMode()!=QuaZip::mdAppend &&
        zip->getMode()!=QuaZip::mdAdd) return false;

    // Controllo la cartella
    QDir directory(dir);
    if (!directory.exists()) return false;

    // Se comprimo anche le sotto cartelle
    if (recursive) {
        // Per ogni sotto cartella
        QFileInfoList files = directory.entryInfoList(QDir::AllDirs|QDir::NoDotAndDotDot);
        Q_FOREACH (QFileInfo file, files) {
            // Comprimo la sotto cartella
            if(!compressSubDir(zip,file.absoluteFilePath(),origDir,recursive)) return false;
        }
    }

    // Per ogni file nella cartella
    QFileInfoList files = directory.entryInfoList(QDir::Files);
    QDir origDirectory(origDir);
    Q_FOREACH (QFileInfo file, files) {
        // Se non e un file o e il file compresso che sto creando
        if(!file.isFile()||file.absoluteFilePath()==zip->getZipName()) continue;

        // Creo il nome relativo da usare all'interno del file compresso
        QString filename = origDirectory.relativeFilePath(file.absoluteFilePath());

        // Comprimo il file
        if (!compressFile(zip,file.absoluteFilePath(),filename)) return false;
    }

    return true;
}
Esempio n. 12
0
int main(int argc, char *argv[]){
 	/* Command line paramters: input file, output file */
 	FILE *fin, *fout;
	/* Compress */
	if(argv[1][1] == 'c'){
		fin = fopen(argv[2], "r");
		fout = fopen(argv[3], "wb");
		compressFile(fin, fout);
	}
	/* Decompress */
	if(argv[1][1] == 'd'){
		fin = fopen(argv[2], "rb");
		fout = fopen(argv[3], "w");
		decompressFile(fin, fout);
	}
	/* Close files */
	fclose(fin);
	fclose(fout);
	return 0;
 }
Esempio n. 13
0
/**OK
 * Comprime i file specificati in files nel file fileCompressed.
 * Se la funzione fallisce restituisce false e cancella il file che si è tentato
 * di creare.
 *
 * La funzione fallisce se:
 * * non si riesce ad aprire l'oggetto zip;
 * * la compressione di un file fallisce;
 * * non si riesce a chiudere l'oggetto zip;
 */
bool JlCompress::compressFiles(QString fileCompressed, QStringList files) {
    // Creo lo zip
    QuaZip* zip  = new QuaZip(QFileInfo(fileCompressed).absoluteFilePath());
    QDir().mkpath(QFileInfo(fileCompressed).absolutePath());
    if(!zip->open(QuaZip::mdCreate)) {
        delete zip;
        QFile::remove(fileCompressed);
        return false;
    }

    // Comprimo i file
    QFileInfo info;
    foreach (QString file, files) {
        info.setFile(file);
        if (!info.exists() || !compressFile(zip,file,info.fileName())) {
            delete zip;
            QFile::remove(fileCompressed);
            return false;
        }
    }
Esempio n. 14
0
static void recurseDirectory(char *dirName)
{
	DIR *dirp, *dirp2;
	struct dirent *dfile;
	char filename[1024];

	dirp = opendir(dirName);

	if (dirp == NULL)
	{
		printf("%s: Directory does not exist or is not accessable\n", dirName);

		exit(1);
	}

	while ((dfile = readdir(dirp)))
	{
		if (dfile->d_name[0] == '.')
		{
			continue;
		}

		snprintf(filename, sizeof(filename), "%s/%s", dirName, dfile->d_name);

		dirp2 = opendir(filename);

		if (dirp2)
		{
			closedir(dirp2);

			recurseDirectory(filename);
		}

		else
		{
			compressFile(filename, dirp);
		}
	}

	closedir(dirp);
}
Esempio n. 15
0
void MainWindow::doCompressFiles()
{
    int		i                   = 0;
    int		err                 = 0;
    int		stopProgress        = 0;

    QString s_Program           = "";

// **********************************************************************************************

    s_Program = findZip( _ZIP_ );

    if ( s_Program != "Zip not found" )
    {
        existsFirstFile( gi_ActionNumber, gs_FilenameFormat, gi_Extension, gsl_FilenameList );

        if ( gsl_FilenameList.count() > 0 )
        {
            initFileProgress( gsl_FilenameList.count(), gsl_FilenameList.at( 0 ), tr( "Compressing files ..." ) );

            while ( ( i < gsl_FilenameList.count() ) && ( stopProgress != _APPBREAK_ ) )
            {
                setStatusBar( tr( "Compress " ) + QDir::toNativeSeparators( gsl_FilenameList.at( i ) ) + tr( " ..." ) );

                compressFile( gsl_FilenameList.at( i ), _ZIP_, s_Program );

                stopProgress = incFileProgress( gsl_FilenameList.count(), ++i );
            }

            resetFileProgress( gsl_FilenameList.count() );
        }
        else
        {
            err = _CHOOSEABORTED_;
        }
    }

    endTool( err, stopProgress, gi_ActionNumber, gs_FilenameFormat, gi_Extension, gsl_FilenameList, tr( "Done" ), tr( "Compressing files was canceled" ), true );

    onError( err );
}
Esempio n. 16
0
void FileEntry::compress(FileProcessor *worker, ParallelFileProcessor *PP)
{
	if( PP->verbose() > 2){
		fprintf( stderr, "[%d] %s", worker->processorID(), fileName.c_str() ); fflush(stderr);
	}
	folderInfo->data_compressed_size = -1;
	compressFile( fileName.c_str(), &fileInfo, folderInfo, worker );
	if( PP->verbose() > 2){
		fputs( " .", stderr ); fflush(stderr);
	}
	if( PP->verbose() ){
		compressedSize = (PP)? process_file_info( fileName.c_str(), NULL, &fileInfo, &PP->jobInfo ) : 0;
#ifndef __APPLE__
		if (folderInfo->data_compressed_size != -1) {
			compressedSize = folderInfo->data_compressed_size;
		}
#endif
		if( PP->verbose() > 2){
			fputs( " .\n", stderr ); fflush(stderr);
		}
	}
}
Esempio n. 17
0
void saveObtainedMedals()
{
	int i, medalCount;
	char medalFile[MAX_PATH_LENGTH];
	Medal *medal;
	FILE *fp;

	snprintf(medalFile, MAX_PATH_LENGTH, "%smedals", gameSavePath);

	fp = fopen(medalFile, "wb");

	if (fp == NULL)
	{
		showErrorAndExit("Could not save Medal data: %s", strerror(errno));
	}

	medalCount = getMedalCount();

	medal = getMedals();

	for (i=0;i<medalCount;i++)
	{
		if (medal[i].obtained == TRUE)
		{
			fprintf(fp, "%s\n", medal[i].code);
		}
	}

	fclose(fp);

	#if DEV == 1
		copyFile(medalFile, "medaldata");
	#endif

	compressFile(medalFile);
}
Esempio n. 18
0
void saveTemporaryData()
{
	char *line, itemName[MAX_MESSAGE_LENGTH], *savePtr;
	char swapFile[MAX_PATH_LENGTH];
	char *mapName = getMapFilename();
	unsigned char *buffer;
	int skipping = FALSE;
	FILE *read;
	FILE *write;

	savePtr = NULL;

	snprintf(swapFile, sizeof(swapFile), "%sswap", gameSavePath);

	read = fopen(tempFile, "rb");

	write = fopen(swapFile, "wb");

	if (read == NULL)
	{
		if (temporaryDataExists == TRUE)
		{
			showErrorAndExit("SAVE TEMP DATA: Could not find persistance file: %s", strerror(errno));
		}
	}

	else
	{
		fclose(read);

		buffer = decompressFile(tempFile);

		if (strlen((char *)buffer) == 0)
		{
			showErrorAndExit("Something went wrong when decompressing the persistance file");
		}

		line = strtok_r((char *)buffer, "\n", &savePtr);

		while (line != NULL)
		{
			if (line[strlen(line) - 1] == '\n')
			{
				line[strlen(line) - 1] = '\0';
			}

			if (line[strlen(line) - 1] == '\r')
			{
				line[strlen(line) - 1] = '\0';
			}

			if (skipping == FALSE)
			{
				sscanf(line, "%s", itemName);

				if (strcmpignorecase("PLAYER_DATA", line) == 0 || strcmpignorecase("PLAYER_INVENTORY", line) == 0 ||
					strcmpignorecase("GLOBAL_TRIGGER", line) == 0 || strcmpignorecase("OBJECTIVE", line) == 0 ||
					strcmpignorecase("PLAYER_LOCATION", line) == 0 || strcmpignorecase("MAP_TRIGGER", line) == 0)
				{
					skipping = TRUE;
				}

				else if (strcmpignorecase("MAP_NAME", itemName) == 0)
				{
					sscanf(line, "%*s %s\n", itemName);

					if (strcmpignorecase(itemName, mapName) == 0)
					{
						skipping = TRUE;
					}

					else
					{
						fprintf(write, "%s\n", line);
					}
				}

				else
				{
					fprintf(write, "%s\n", line);
				}
			}

			else
			{
				sscanf(line, "%s", itemName);

				if (strcmpignorecase("MAP_NAME", itemName) == 0)
				{
					sscanf(line, "%*s %s\n", itemName);

					if (strcmpignorecase(itemName, mapName) != 0)
					{
						skipping = FALSE;

						fprintf(write, "%s\n", line);
					}
				}
			}

			line = strtok_r(NULL, "\n", &savePtr);
		}

		free(buffer);

		if (remove(tempFile) != 0)
		{
			showErrorAndExit("Could not remove temporary file");
		}
	}

	fprintf(write, "MAP_NAME %s\n", mapName);

	fprintf(write, "ENTITY_DATA\n");

	/* Now write out all of the Entities */

	writeEntitiesToFile(write);

	/* Now the targets */

	writeTargetsToFile(write);

	/* And the triggers */

	writeTriggersToFile(write);

	fclose(write);

	if (rename(swapFile, tempFile) != 0)
	{
		showErrorAndExit("Could not rename temporary file");
	}

	#if DEV == 1
		copyFile(tempFile, "tmpdata");
	#endif

	compressFile(tempFile);

	temporaryDataExists = TRUE;
}
Esempio n. 19
0
static void patchSaveGame(char *saveFile, double version)
{
	char location[MAX_VALUE_LENGTH], *line, *savePtr, itemName[MAX_MESSAGE_LENGTH], *returnedName, mapName[MAX_VALUE_LENGTH];
	unsigned char *buffer, *originalBuffer;
	int savedLocation = FALSE, saveMap;
	FILE *newSave;

	savePtr = NULL;

	freeGameResources();

	newSave = fopen(tempFile, "wb");

	buffer = decompressFile(saveFile);

	originalBuffer = malloc((strlen((char *)buffer) + 1) * sizeof(unsigned char));

	if (originalBuffer == NULL)
	{
		showErrorAndExit("Failed to allocate %d bytes to patch save game", (int)((strlen((char *)buffer) + 1) * sizeof(unsigned char)));
	}

	strcpy((char *)originalBuffer, (char *)buffer);

	line = strtok_r((char *)buffer, "\n", &savePtr);

	returnedName = NULL;

	mapName[0] = '\0';

	while (line != NULL)
	{
		if (line[strlen(line) - 1] == '\n')
		{
			line[strlen(line) - 1] = '\0';
		}

		if (line[strlen(line) - 1] == '\r')
		{
			line[strlen(line) - 1] = '\0';
		}

		sscanf(line, "%s", itemName);

		if (strcmpignorecase("PLAYER_LOCATION", itemName) == 0)
		{
			sscanf(line, "%*s %s\n", location);
		}

		else if (strcmpignorecase("MAP_NAME", itemName) == 0)
		{
			saveMap = TRUE;

			if (strlen(mapName) == 0 || strcmpignorecase(line, mapName) == 0)
			{
				sscanf(line, "%*s %s\n", itemName);

				returnedName = loadResources(savePtr);

				if (returnedName != NULL)
				{
					STRNCPY(mapName, returnedName, sizeof(mapName));
				}

				/* Rewind to start */

				free(buffer);

				buffer = malloc((strlen((char *)originalBuffer) + 1) * sizeof(unsigned char));

				if (buffer == NULL)
				{
					showErrorAndExit("Failed to allocate %d bytes to patch save game", (int)((strlen((char *)originalBuffer) + 1) * sizeof(unsigned char)));
				}

				strcpy((char *)buffer, (char *)originalBuffer);

				line = strtok_r((char *)buffer, "\n", &savePtr);

				/* Load up the patch file */

				saveMap = patchEntities(version, itemName);

				if (saveMap == FALSE)
				{
					snprintf(itemName, sizeof(itemName), "%ld_old", game.playTime * SDL_GetTicks());
				}

				if (savedLocation == FALSE)
				{
					fprintf(newSave, "VERSION %0.2f\n", version);

					fprintf(newSave, "PLAY_TIME %ld\n", game.playTime);

					fprintf(newSave, "PLAYER_KILLS %d\n", game.kills);

					fprintf(newSave, "BATS_DROWNED %d\n", game.batsDrowned);

					fprintf(newSave, "TIMES_EATEN %d\n", game.timesEaten);

					fprintf(newSave, "DISTANCE_TRAVELLED %u\n", game.distanceTravelled);

					fprintf(newSave, "ATTACKS_BLOCKED %d\n", game.attacksBlocked);

					fprintf(newSave, "SLIME_TIME %d\n", game.timeSpentAsSlime);

					fprintf(newSave, "ARROWS_FIRED %d\n", game.arrowsFired);

					fprintf(newSave, "SECRETS_FOUND %d\n", game.secretsFound);

					fprintf(newSave, "CONTINUES %d\n", game.continues);

					fprintf(newSave, "CHEATING %d\n", game.cheating);

					fprintf(newSave, "PLAYER_LOCATION %s\n", location);

					savedLocation = TRUE;
				}

				fprintf(newSave, "MAP_NAME %s\n", itemName);

				if (strcmpignorecase(itemName, location) == 0)
				{
					fprintf(newSave, "PLAYER_DATA\n");

					writePlayerToFile(newSave);

					fprintf(newSave, "PLAYER_INVENTORY\n");

					writeInventoryToFile(newSave);
				}

				fprintf(newSave, "ENTITY_DATA\n");

				/* Now write out all of the Entities */

				writeEntitiesToFile(newSave);

				/* Now the targets */

				writeTargetsToFile(newSave);

				/* And the triggers */

				writeTriggersToFile(newSave);

				/* Add the global triggers */

				writeGlobalTriggersToFile(newSave);

				/* Add the map triggers */

				writeMapTriggersToFile(newSave);

				/* Add the objectives */

				writeObjectivesToFile(newSave);

				freeLevelResources();

				if (returnedName == NULL)
				{
					break;
				}
			}
		}

		line = strtok_r(NULL, "\n", &savePtr);
	}

	free(buffer);

	free(originalBuffer);

	fclose(newSave);

	#if DEV == 1
		copyFile(tempFile, "tmpdata");
	#endif

	copyFile(tempFile, saveFile);

	compressFile(saveFile);
}
Esempio n. 20
0
File: main.c Progetto: rarry/it
int main()
{


    char * inFp = "C:\\abc.txt";
    //char * inFpZeroes= "C:\\abc_zeroes.txt";
    char * inFpCrc = "C:\\abc_crc.txt";
    char * outFp = "C:\\abc_compressed.txt";
    char * decompressedFpCrc = "C:\\abc_decompressed_crc.txt";
    char * decompressedFp = "C:\\abc_decompressed.txt";


    copyFile(inFp, inFpCrc);
    //appendZeroes(inFpZeroes, SIZECRC);
    unsigned char * restPoly = calculateCrc(inFp);
    printf("Generated polynomial:\n");
    printPolynomial(restPoly, SIZECRC);

    appendCrcToFile(inFpCrc, SIZECRC, restPoly);

    int lettersFrequencies[LETTERS_COUNT]; // = {81, 15, 28, 43, 128, 23, 20, 61, 71, 2, 1, 40, 24, 69, 76, 20, 1, 61, 64, 91, 28, 10, 24, 1, 20, 1, 130};;
    //char letters[LETTERS_COUNT] = {'?', '?', '?', '?', '?', '?', '?', '?', '?', '?','?', '?', '?', '?', '?','?', '?', '?', '?', '?','?', '?', '?', '?', '?','?', '?', '?', '?', '?', '?', '?', '!', '"', '#', '$', '%', '&', '(', ')', '*', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', ' '};
    //printTabInt(lettersFrequencies, LETTERS_COUNT);
    //printTabChar(letters, LETTERS_COUNT);

    //printf("Letter indices: ");

    calculateFreq(inFpCrc, lettersFrequencies);
    //printTabInt(lettersFrequencies, 255);

    Node *nodes[LETTERS_COUNT];
    int i;
    for(i=0; i<LETTERS_COUNT; i++)
    {
        nodes[i] = malloc(sizeof(Node));
        nodes[i]->value = lettersFrequencies[i];
        nodes[i]->letterIndex = i;
        nodes[i]->left = NULL;
        nodes[i]->right = NULL;
    }

    //printLetterIndices(nodes);
    Node *tree = buildHuffmanTree(nodes);

    int codeTable[LETTERS_COUNT];
    int invertedCodeTable2[LETTERS_COUNT];
    resetIntTable(codeTable, LETTERS_COUNT);

    //printf("codeTable: \n");
    //printTabInt(codeTable, LETTERS_COUNT);
    fillTable(codeTable, tree, 0);
    invertCodeTable(codeTable, invertedCodeTable2);


    //printf("codeTable: \n");
    //printTabInt(codeTable, LETTERS_COUNT);

    //printf("inverted codeTable: \n");
    //printTabInt(invertedCodeTable2, LETTERS_COUNT);
    //printCodeTable(letters, codeTable, LETTERS_COUNT);
    //printCodeTableForIdx(codeTable, LETTERS_COUNT);
    //printTabInt(codeTable, LETTERS_COUNT);




    //createCrcFile(inFpCrc, SIZECRC, restPoly);
    //appendFileToFile(inFp, inFpCrc);



    compressFile(inFpCrc, outFp, invertedCodeTable2);
    printf("\n\ndecompressed file:\n");
    decompressFile(outFp, decompressedFpCrc, tree);

    unsigned char * restPolyFromDec = calulateRest(decompressedFpCrc);
    printf("\n\nRest from decopressed file:\n");
    printPolynomial(restPolyFromDec, SIZECRC);

    if(!isIntegral()){
        printf("Integrity check failed!");
        exit(EXIT_FAILURE);
    }else{
        copySkip(decompressedFpCrc, decompressedFp, SIZECRC);
    }

    //checkIntegrity();


    //FILE * output = fopen("C:\\codeblocks\\Huffman\\huffman\\to.txt","w");
    //compressFile(input, output, codeTable);


    return 0;
}
Esempio n. 21
0
int main ( int argc, const char** argv ) {


	int ret;
	int i;

	uint32_t mode= MODE_DEFAULT;
	const char* command= NULL;
	const char* p;

	uint32_t len;
	const char* infilename;
	char* outfilename= NULL;

	int keep= 0;
	int zlevel= ZLEVEL;


	if ( 1 >= argc ) {

			SHOW_HELPTEXT;
			return 0;
	}
	

	/* collect parameters */
	for ( i= 1; i < argc; i++ ) {

		if ( 0 == strcmp( "-h", argv[i] ) || 0 == strcmp( "--help", argv[i] ) ) {

			SHOW_HELPTEXT;
			exit( 0 );

		} else 

		if ( 0 == strcmp( "-k", argv[i] ) ) {

			keep= 1;

		} else 

		if ( 0 == strcmp( "-c", argv[i] ) ) {

			if ( MODE_DEFAULT == mode ) {

				mode= MODE_COMPRESS;

			} else {

				fprintf( stderr, "mode already set, cannot re-set, ignoring '-c'\n" );
			}

		} else 

		if ( 0 == strcmp( "-d", argv[i] ) ) {

			if ( MODE_DEFAULT == mode ) {

				mode= MODE_DECOMPRESS;

			} else {

				fprintf( stderr, "mode already set, cannot re-set, ignoring '-d'\n" );
			}

		} else 

		if ( ( '-' == argv[i][0] ) && ( '0' <= argv[i][1] ) && ( '9' >= argv[i][1] ) )  {

			zlevel= (int) ( argv[i][1] - '0' );

		} else 
		
		if ( 0 == strcmp( "-V", argv[i] ) ) {
		
			printf( "%u.%u.%u \"%s\"\n", OTF_VERSION_MAYOR, OTF_VERSION_MINOR,
				OTF_VERSION_SUB, OTF_VERSION_STRING);
			exit( 0 );
		}
	}

	/* look at argv[0], mode defaults to compress/decomress according to command name */
	if ( MODE_DEFAULT == mode ) {
	
		p= strrchr( argv[0], '/' );
		command = NULL != p ? p+1 : argv[0];

		if ( 0 == strcmp( "otfcompress", command ) ) {

			mode= MODE_COMPRESS;
		}

		if ( 0 == strcmp( "otfdecompress", command ) ) {

			mode= MODE_DECOMPRESS;
		}

		if ( 0 == strcmp( "otfuncompress", command ) ) {

			mode= MODE_DECOMPRESS;
		}
	}


	/* files to (de)compress */
	for ( i= 1; i < argc; i++ ) {

		if ( '-' == argv[i][0] ) {

			/* switches already handled */

		} else {
		
			/* assume argument is a file name */

			switch ( mode ) {

			case MODE_DECOMPRESS:

				/* decompress file */
				infilename= argv[i];
				len= (uint32_t) strlen( infilename );
				outfilename= realloc( outfilename, len +1 );
				assert( NULL != outfilename );

				/* built outfilename */
				strncpy( outfilename, infilename, len +1 );

				/* find and remove ".z" at the end */
				if ( ( 2 >= len ) || ( 0 != strcmp( ".z", outfilename +len -2 ) ) ) {
				
					fprintf( stderr, "ERROR: no trailing '.z' in filename '%s', rejecting\n", 
						infilename );

					continue;
				}

				outfilename[len -2]= '\0';

				fprintf( stdout, "decompress \"%s\" -> \"%s\"\n", 
					infilename, outfilename );

				ret= decompressFile( infilename, outfilename, BUFFERSIZE );

				if ( 0 == ret ) {

					if ( keep ) {

						/* keep compressed file */

					} else {

						/* remove compressed file */
						ret= unlink( infilename );

						if ( 0 != ret ) {

							fprintf( stderr, "error removing '%s'\n", infilename );
						}
					}

				} else {

					fprintf( stderr, "decompress error for file '%s'\n", infilename );
				} 

				break;

			case MODE_COMPRESS:
			case MODE_DEFAULT:
			default:

				/* compress file */
				infilename= argv[i];
				len= (uint32_t) strlen( infilename );

				/* check for ".z" at the end and refuse compression if found */
				if ( ( 2 < len ) && ( 0 == strcmp( ".z", infilename +len -2 ) ) ) {
				
					fprintf( stderr, "ERROR: found '.z' suffix in filename, "
						"file '%s' seems already compressed, skip\n", 
						infilename );

					continue;
				}

				outfilename= realloc( outfilename, len +3 );
				assert( NULL != outfilename );

				/* built outfilename */
				strncpy( outfilename, infilename, len +1 );
				strncpy( outfilename +len, ".z", 3 );
				
				fprintf( stdout, "compress \"%s\" -> \"%s\"\n", 
					infilename, outfilename );

				ret= compressFile( infilename, outfilename, zlevel, BUFFERSIZE );

				if ( 0 == ret ) {

					if ( keep ) {

						/* rename original file */

						outfilename= realloc( outfilename, len +3 );
						assert( NULL != outfilename );

						/* built outfilename */
						strncpy( outfilename, infilename, len +1 );
						strncpy( outfilename +len, ".original", 10 );

						ret= rename( infilename, outfilename );
						
						if ( 0 != ret ) {

							fprintf( stderr, "error renaming '%s' to '%s'\n", 
								infilename, outfilename );
						}
						
					} else {

						/* remove uncompressed */

						ret= unlink( infilename );

						if ( 0 != ret ) {

							fprintf( stderr, "error removing '%s'\n", infilename );
						}
					}

				} else {

					fprintf( stderr, "compress error for file '%s'\n", infilename );
				}

				break;
			}
		}
	}

	free( outfilename );
	outfilename= NULL;
	infilename= NULL;

	return 0;
}
Esempio n. 22
0
int main(int argc, char *argv[])
{
	int i;
	int32_t length;
	char versionName[5];
	FILE *versionFile;

	if (argc == 3)
	{
		if (strcmpignorecase(argv[1], "-test") == 0)
		{
			testPak(argv[2]);

			exit(0);
		}
	}

	else if (argc < 3)
	{
		printf("Usage   : pak <directory names> <outputname>\n");
		printf("Example : pak data music gfx sound font edgar.pak\n");

		exit(1);
	}

	pak = fopen(argv[argc - 1], "wb");

	totalFiles = 0;

	for (i=1;i<argc-1;i++)
	{
		totalFiles += countFiles(argv[i]);
	}

	totalFiles++;

	printf("Will compress %d files\n", totalFiles);

	printf("Compressing 00%%...\r");

	fileData = malloc(totalFiles * sizeof(FileData));

	if (fileData == NULL)
	{
		printf("Failed to create File Data\n");

		exit(1);
	}

	atexit(cleanup);

	snprintf(versionName, sizeof(versionName), "%0.2f", VERSION);

	versionFile = fopen(versionName, "wb");

	fprintf(versionFile, "%s", versionName);

	fclose(versionFile);

	for (i=1;i<argc-1;i++)
	{
		recurseDirectory(argv[i]);
	}

	compressFile(versionName, NULL);

	remove(versionName);

	length = ftell(pak);

	for (i=0;i<totalFiles;i++)
	{
		if (fileData[i].fileSize == 0)
		{
			break;
		}

		fileData[i].offset = SWAP32(fileData[i].offset);
		fileData[i].compressedSize = SWAP32(fileData[i].compressedSize);
		fileData[i].fileSize = SWAP32(fileData[i].fileSize);

		fwrite(&fileData[i], sizeof(FileData), 1, pak);
	}

	length = SWAP32(length);
	totalFiles = SWAP32(totalFiles);

	fwrite(&length, sizeof(int32_t), 1, pak);
	fwrite(&totalFiles, sizeof(int32_t), 1, pak);

	fclose(pak);

	printf("Compressing 100%%\nCompleted\n");

	return 0;
}
Esempio n. 23
0
int C3dsTool::Action()
{
	if (m_eAction == kActionExtract)
	{
		if (!extractFile())
		{
			printf("ERROR: extract file failed\n\n");
			return 1;
		}
	}
	if (m_eAction == kActionCreate)
	{
		if (!createFile())
		{
			printf("ERROR: create file failed\n\n");
			return 1;
		}
	}
	if (m_eAction == kActionEncrypt)
	{
		if (!encryptFile())
		{
			printf("ERROR: encrypt file failed\n\n");
			return 1;
		}
	}
	if (m_eAction == kActionUncompress)
	{
		if (!uncompressFile())
		{
			printf("ERROR: uncompress file failed\n\n");
			return 1;
		}
	}
	if (m_eAction == kActionCompress)
	{
		if (!compressFile())
		{
			printf("ERROR: compress file failed\n\n");
			return 1;
		}
	}
	if (m_eAction == kActionTrim)
	{
		if (!trimFile())
		{
			printf("ERROR: trim file failed\n\n");
			return 1;
		}
	}
	if (m_eAction == kActionPad)
	{
		if (!padFile())
		{
			printf("ERROR: pad file failed\n\n");
			return 1;
		}
	}
	if (m_eAction == kActionDiff)
	{
		if (!diffFile())
		{
			printf("ERROR: create patch file failed\n\n");
			return 1;
		}
	}
	if (m_eAction == kActionPatch)
	{
		if (!patchFile())
		{
			printf("ERROR: apply patch file failed\n\n");
			return 1;
		}
	}
	if (m_eAction == kActionSample)
	{
		return sample();
	}
	if (m_eAction == kActionHelp)
	{
		return Help();
	}
	return 0;
}
Esempio n. 24
0
bool FstReader::zip() {
    // File Dialog
    QString filename = QFileDialog::getOpenFileName(NULL,
                                                    "Select your .fst file ...",
                                                    QStandardPaths::writableLocation(QStandardPaths::DownloadLocation),
                                                    "*.fst");
    
    // First we check the FST file
    QFile fst(filename);
    if (!fst.open(QFile::ReadOnly | QFile::Text)) {
        qDebug() << "[ERROR] Could not open FST file : " << fst.fileName();
        return false;
    }
    
    // Compress and copy the fst
    if (!compressFile(QFileInfo(fst).filePath(), _zipDir.path() + "/" + QFileInfo(fst).fileName())) {
        return false;
    }
    _totalSize += QFileInfo(fst).size();
    if (!addPart(_zipDir.path() + "/" + QFileInfo(fst).fileName(),
                 QString("fst"))) {
        return false;
    }
    qDebug() << "Reading FST file : " << QFileInfo(fst).filePath();
    
    // Let's read through the FST file
    QTextStream stream(&fst);
    QList<QString> line;
    while (!stream.atEnd()) {
        line = stream.readLine().split(QRegExp("[ =]"), QString::SkipEmptyParts);
        if (line.isEmpty()) {
            continue;
        }
        
        if (_totalSize > MAX_SIZE) {
            qDebug() << "[ERROR] Model too big, over " << MAX_SIZE << " Bytes.";
            return false;
        }
        
        // according to what is read, we modify the command
        if (line.first() == NAME_FIELD) {
            QHttpPart textPart;
            textPart.setHeader(QNetworkRequest::ContentDispositionHeader, "form-data;"
                               " name=\"model_name\"");
            textPart.setBody(line[1].toUtf8());
            _dataMultiPart->append(textPart);
        } else if (line.first() == FILENAME_FIELD) {
            QFileInfo fbx(QFileInfo(fst).path() + "/" + line[1]);
            if (!fbx.exists() || !fbx.isFile()) { // Check existence
                qDebug() << "[ERROR] FBX file " << fbx.absoluteFilePath() << " doesn't exist.";
                return false;
            }
            // Compress and copy
            if (!compressFile(fbx.filePath(), _zipDir.path() + "/" + line[1])) {
                return false;
            }
            _totalSize += fbx.size();
            if (!addPart(_zipDir.path() + "/" + line[1], "fbx")) {
                return false;
            }
        } else if (line.first() == TEXDIR_FIELD) { // Check existence
            QFileInfo texdir(QFileInfo(fst).path() + "/" + line[1]);
            if (!texdir.exists() || !texdir.isDir()) {
                qDebug() << "[ERROR] Texture directory " << texdir.absolutePath() << " doesn't exist.";
                return false;
            }
            if (!addTextures(texdir)) { // Recursive compress and copy
                return false;
            }
        } else if (line.first() == LOD_FIELD) {
            QFileInfo lod(QFileInfo(fst).path() + "/" + line[1]);
            if (!lod.exists() || !lod.isFile()) { // Check existence
                qDebug() << "[ERROR] FBX file " << lod.absoluteFilePath() << " doesn't exist.";
                return false;
            }
            // Compress and copy
            if (!compressFile(lod.filePath(), _zipDir.path() + "/" + line[1])) {
                return false;
            }
            _totalSize += lod.size();
            if (!addPart(_zipDir.path() + "/" + line[1], QString("lod%1").arg(++_lodCount))) {
                return false;
            }
        }
    }
    
    _readyToSend = true;
    return true;
}
Esempio n. 25
0
int main ( int argc, char** argv ) {


	int ret;
	int i;

	uint32_t mode= MODE_DEFAULT;
	const char* command= NULL;
	const char* p;

	const char* infilename;
	char outfilename[OTF_PATH_MAX];
	char* outdir= NULL;

	int keep= 0;
	int zlevel= ZLEVEL;


	if ( 1 >= argc ) {

			SHOW_HELPTEXT;
			return 0;
	}
	

	/* collect parameters */
	for ( i= 1; i < argc; i++ ) {

		if ( 0 == strcmp( "-h", argv[i] ) || 0 == strcmp( "--help", argv[i] ) ) {

			SHOW_HELPTEXT;
			exit( 0 );

		} else 

		if ( 0 == strcmp( "-k", argv[i] ) ) {

			keep= 1;

		} else 

		if ( 0 == strcmp( "-o", argv[i] ) && i < argc -1 ) {

			outdir= argv[++i];
			keep= 1;

		} else 

		if ( 0 == strcmp( "-c", argv[i] ) ) {

			if ( MODE_DEFAULT == mode ) {

				mode= MODE_COMPRESS;

			} else {

				fprintf( stderr, "mode already set, cannot re-set, ignoring '-c'\n" );
			}

		} else 

		if ( 0 == strcmp( "-d", argv[i] ) ) {

			if ( MODE_DEFAULT == mode ) {

				mode= MODE_DECOMPRESS;

			} else {

				fprintf( stderr, "mode already set, cannot re-set, ignoring '-d'\n" );
			}

		} else 

		if ( ( '-' == argv[i][0] ) && ( '0' <= argv[i][1] ) && ( '9' >= argv[i][1] ) )  {

			zlevel= (int) ( argv[i][1] - '0' );

		} else 
		
		if ( 0 == strcmp( "-V", argv[i] ) ) {
		
			printf( "%u.%u.%u \"%s\"\n", OTF_VERSION_MAJOR, OTF_VERSION_MINOR,
				OTF_VERSION_SUB, OTF_VERSION_STRING);
			exit( 0 );
		}
	}

	/* look at argv[0], mode defaults to compress/decomress according to command name */
	if ( MODE_DEFAULT == mode ) {
	
		p= strrchr( argv[0], '/' );
		command = NULL != p ? p+1 : argv[0];

		if ( 0 == strcmp( "otfdecompress", command ) || 0 == strcmp( "otfdecompress.exe", command ) ) {

			mode= MODE_DECOMPRESS;

		}

	}


	/* files to (de)compress */
	for ( i= 1; i < argc; i++ ) {

		if ( '-' == argv[i][0] ) {

			/* switches already handled */

			if ( outdir != NULL && 0 == strcmp( argv[i], "-o" ) ) {

				/* skip value of option '-o' */
				i++;

			}

		} else {
		
			/* assume argument is a file name */

			infilename= argv[i];

			/* compose output file name */

			if ( NULL == outdir ) {

				snprintf( outfilename, sizeof( outfilename ) -1, "%s",
					  infilename );

			} else {

				p= strrchr( infilename, '/' );
				if ( NULL != p ) p++;
				else p= infilename;
				
				snprintf( outfilename, sizeof( outfilename ) -1, "%s/%s",
					  outdir, p );

			}

			switch ( mode ) {

			case MODE_DECOMPRESS:

				/* decompress file */

				/* check for ".z" at the end and refuse uncompression if not found */
				if ( ( 2 >= strlen( infilename ) ) ||
				     ( 0 != strcmp( infilename +strlen( infilename ) -2, ".z" ) ) ) {
				
					fprintf( stderr, "ERROR: no trailing '.z' in filename '%s', rejecting\n", 
						 infilename );

					continue;
				}

				/* cut trailing '.z' from output file name */
				outfilename[strlen( outfilename )-2] = '\0';

				fprintf( stdout, "decompress \"%s\" -> \"%s\"\n", 
					infilename, outfilename );

				ret= decompressFile( infilename, outfilename, BUFFERSIZE );

				if ( 0 == ret ) {

					if ( keep ) {

						/* keep compressed file */

					} else {

						/* remove compressed file */
						ret= unlink( infilename );

						if ( 0 != ret ) {

							fprintf( stderr, "error removing '%s'\n", infilename );
						}
					}

				} else {

					fprintf( stderr, "decompress error for file '%s'\n", infilename );
				} 

				break;

			case MODE_COMPRESS:
			case MODE_DEFAULT:
			default:

				/* compress file */

				/* check for ".z" at the end and refuse compression if found */
				if ( ( 2 < strlen( infilename ) ) &&
				     ( 0 == strcmp( infilename +strlen( infilename ) -2, ".z" ) ) ) {
				
					fprintf( stderr, "ERROR: found '.z' suffix in filename, "
						"file '%s' seems already compressed, skip\n", 
						infilename );

					continue;
				}

				/* add trailing '.z' to output file name */
				if ( strlen( outfilename ) +2 < sizeof( outfilename ) )
					strcat( outfilename, ".z" );

				fprintf( stdout, "compress \"%s\" -> \"%s\"\n", 
					infilename, outfilename );

				ret= compressFile( infilename, outfilename, zlevel, BUFFERSIZE );

				if ( 0 == ret ) {

					if ( keep ) {

						if ( outdir ) {

							/* keep uncompressed file */

						} else {

							/* rename original file */

							snprintf( outfilename, sizeof( outfilename ) -1, "%s.original",
								  infilename );

							ret= rename( infilename, outfilename );
						
							if ( 0 != ret ) {

								fprintf( stderr, "error renaming '%s' to '%s'\n", 
									 infilename, outfilename );

							}

						}

					} else {

						/* remove uncompressed */

						ret= unlink( infilename );

						if ( 0 != ret ) {

							fprintf( stderr, "error removing '%s'\n", infilename );
						}
					}

				} else {

					fprintf( stderr, "compress error for file '%s'\n", infilename );
				}

				break;
			}
		}
	}

	return 0;
}
Esempio n. 26
0
void saveGame(int slot)
{
	char itemName[MAX_MESSAGE_LENGTH], *line, *savePtr;
	char saveFile[MAX_PATH_LENGTH];
	char *mapName = getMapFilename();
	char tempSaveFile[MAX_PATH_LENGTH];
	int i;
	unsigned char *buffer;
	int skipping = FALSE;
	FILE *read;
	FILE *write;

	savePtr = NULL;

	if (slot == -1)
	{
		for (i=1001;;i++)
		{
			snprintf(saveFile, sizeof(saveFile), "%ssave%d", gameSavePath, i);

			read = fopen(saveFile, "rb");

			if (read == NULL)
			{
				break;
			}

			else
			{
				fclose(read);
			}
		}
	}

	else
	{
		/* Backup older save */

		snprintf(saveFile, sizeof(saveFile), "%ssave%d", gameSavePath, slot);

		snprintf(tempSaveFile, sizeof(tempSaveFile), "%stempsave%d", gameSavePath, slot);
	}

	write = fopen(tempSaveFile, "wb");

	fprintf(write, "VERSION %0.2f\n", VERSION);

	fprintf(write, "PLAY_TIME %ld\n", game.playTime);

	fprintf(write, "PLAYER_KILLS %d\n", game.kills);

	fprintf(write, "BATS_DROWNED %d\n", game.batsDrowned);

	fprintf(write, "TIMES_EATEN %d\n", game.timesEaten);

	fprintf(write, "DISTANCE_TRAVELLED %u\n", game.distanceTravelled);

	fprintf(write, "ATTACKS_BLOCKED %d\n", game.attacksBlocked);

	fprintf(write, "SLIME_TIME %d\n", game.timeSpentAsSlime);

	fprintf(write, "ARROWS_FIRED %d\n", game.arrowsFired);

	fprintf(write, "SECRETS_FOUND %d\n", game.secretsFound);

	fprintf(write, "CONTINUES %d\n", game.continues);

	fprintf(write, "CHEATING %d\n", game.cheating);

	fprintf(write, "PLAYER_LOCATION %s\n", mapName);

	read = fopen(tempFile, "rb");

	if (read == NULL)
	{
		if (temporaryDataExists == TRUE)
		{
			showErrorAndExit("SAVE GAME: Could not find persistance file: %s", strerror(errno));
		}
	}

	else
	{
		fclose(read);

		buffer = decompressFile(tempFile);

		line = strtok_r((char *)buffer, "\n", &savePtr);

		while (line != NULL)
		{
			if (line[strlen(line) - 1] == '\n')
			{
				line[strlen(line) - 1] = '\0';
			}

			if (line[strlen(line) - 1] == '\r')
			{
				line[strlen(line) - 1] = '\0';
			}

			if (skipping == FALSE)
			{
				sscanf(line, "%s", itemName);

				if (strcmpignorecase("PLAYER_DATA", itemName) == 0 || strcmpignorecase("PLAYER_INVENTORY", itemName) == 0 ||
					strcmpignorecase("PLAYER_LOCATION", itemName) == 0 || strcmpignorecase("VERSION", itemName) == 0)
				{
					skipping = TRUE;
				}

				else if (strcmpignorecase("MAP_NAME", itemName) == 0)
				{
					sscanf(line, "%*s %s\n", itemName);

					if (strcmpignorecase(itemName, mapName) == 0)
					{
						skipping = TRUE;
					}

					else
					{
						fprintf(write, "%s\n", line);
					}
				}

				else
				{
					fprintf(write, "%s\n", line);
				}
			}

			else
			{
				sscanf(line, "%s", itemName);

				if (strcmpignorecase("MAP_NAME", itemName) == 0)
				{
					sscanf(line, "%*s %s\n", itemName);

					if (strcmpignorecase(itemName, mapName) != 0)
					{
						skipping = FALSE;

						fprintf(write, "%s\n", line);
					}
				}
			}

			line = strtok_r(NULL, "\n", &savePtr);
		}

		free(buffer);
	}

	/* Save the player's position */

	fprintf(write, "MAP_NAME %s\n", mapName);

	fprintf(write, "PLAYER_DATA\n");

	writePlayerToFile(write);

	fprintf(write, "INVENTORY_INDEX %d\n", getInventoryIndex());

	fprintf(write, "PLAYER_INVENTORY\n");

	writeInventoryToFile(write);

	fprintf(write, "ENTITY_DATA\n");

	/* Now write out all of the Entities */

	writeEntitiesToFile(write);

	/* Now the targets */

	writeTargetsToFile(write);

	/* And the triggers */

	writeTriggersToFile(write);

	/* Add the global triggers */

	writeGlobalTriggersToFile(write);

	/* Add the map triggers */

	writeMapTriggersToFile(write);

	/* Add the objectives */

	writeObjectivesToFile(write);

	/* Save the player data */

	fclose(write);

	#if DEV == 1
		copyFile(tempSaveFile, "savedata");
	#endif

	compressFile(tempSaveFile);

	copyFile(tempSaveFile, saveFile);

	remove(tempSaveFile);

	updateSaveFileIndex(slot);
}