Ejemplo n.º 1
0
int main( int argc, char* argv[] )
{
	Allocator::Enable( true );
	Allocator::GetDefault().Initialize( g_MainMemorySize );

	Main( argc, argv );

#if DO_PROFILING
#if BUILD_DEBUG	// I ship Release ContentSyncer, not Final.
	Profiler::GetInstance()->Dump( FileStream( "profiler.txt", FileStream::EFM_Write ) );
#endif
	Profiler::DeleteInstance();
#endif

#if BUILD_DEBUG
	Allocator::GetDefault().Report( FileStream( "content-syncer-memory-exit-report.txt", FileStream::EFM_Write ) );
#endif
	DEBUGASSERT( Allocator::GetDefault().CheckForLeaks() );
	Allocator::GetDefault().ShutDown();

	DEBUGASSERT( _CrtCheckMemory() );
	DEBUGASSERT( !_CrtDumpMemoryLeaks() );

	return 0;
}
Ejemplo n.º 2
0
int FilePacker::UnpackFile( const char* PackFilename )
{
	if( FileUtil::Exists( PackFilename ) )
	{
		ReadPackFile( FileStream( PackFilename, FileStream::EFM_Read ) );
		for( uint i = 0; i < m_FileEntries.Size(); ++i )
		{
			SPackageFileEntry& FileEntry = m_FileEntries[i];
			FileUtil::RecursiveMakePath( FileEntry.m_Filename.CStr() );
			WriteUnpackedFile( FileStream( FileEntry.m_Filename.CStr(), FileStream::EFM_Write ), FileEntry );
		}
	}
	return 0;
}
Ejemplo n.º 3
0
void EldritchFramework::WritePrefsConfig() {
  const SimpleString PrefsConfigFilename =
      GetSaveLoadPath() + SimpleString("prefs.cfg");
  const FileStream PrefsConfigStream =
      FileStream(PrefsConfigFilename.CStr(), FileStream::EFM_Write);

  PrefsConfigStream.PrintF(
      "# This file is automatically generated.\n# You may delete it to restore "
      "defaults.\n\n");

  ConfigManager::BeginWriting();

  ConfigManager::Write(PrefsConfigStream, "Language");
  ConfigManager::Write(PrefsConfigStream, "DisplayWidth");
  ConfigManager::Write(PrefsConfigStream, "DisplayHeight");
  ConfigManager::Write(PrefsConfigStream, "Fullscreen");
  ConfigManager::Write(PrefsConfigStream, "OpenGL");
  ConfigManager::Write(PrefsConfigStream, "Brightness");
  ConfigManager::Write(PrefsConfigStream, "FOV");
  ConfigManager::Write(PrefsConfigStream, "VSync");
  ConfigManager::Write(PrefsConfigStream, "MouseSpeed");
  ConfigManager::Write(PrefsConfigStream, "ControllerSpeed");
  ConfigManager::Write(PrefsConfigStream, "InvertY");
  ConfigManager::Write(PrefsConfigStream, "MasterVolume");
  ConfigManager::Write(PrefsConfigStream, "MusicVolume");

  m_InputSystem->WriteConfigBinds(PrefsConfigStream);
}
Ejemplo n.º 4
0
    bool TileSequenceSave(TitleSequence * seq)
    {
        bool success = false;
        utf8 * script = LegacyScriptWrite(seq);
        if (seq->IsZip)
        {
            IZipArchive * zip = Zip::TryOpen(seq->Path, ZIP_ACCESS_WRITE);
            zip->SetFileData("script.txt", script, String::SizeOf(script));
            delete zip;
            success = true;
        }
        else
        {
            utf8 scriptPath[MAX_PATH];
            String::Set(scriptPath, sizeof(scriptPath), seq->Path);
            Path::Append(scriptPath, sizeof(scriptPath), "script.txt");

            try
            {
                auto fs = FileStream(scriptPath, FILE_MODE_WRITE);
                fs.Write(script, String::SizeOf(script));
                success = true;
            }
            catch (Exception)
            {
            }
        }

        Memory::Free(script);
        return success;
    }
Ejemplo n.º 5
0
LanguagePack * LanguagePack::FromFile(uint16 id, const utf8 * path)
{
    assert(path != nullptr);

    // Load file directly into memory
    utf8 * fileData = nullptr;
    try
    {
        FileStream fs = FileStream(path, FILE_MODE_OPEN);
        
        size_t fileLength = (size_t)fs.GetLength();
        if (fileLength > MAX_LANGUAGE_SIZE)
        {
            throw IOException("Language file too large.");
        }

        fileData = Memory::Allocate<utf8>(fileLength + 1);
        fs.Read(fileData, fileLength);
        fileData[fileLength] = '\0';
    }
    catch (Exception ex)
    {
        Memory::Free(fileData);
        log_error("Unable to open %s: %s", path, ex.GetMessage());
        return nullptr;
    }

    // Parse the memory as text
    LanguagePack * result = FromText(id, fileData);

    Memory::Free(fileData);
    return result;
}
Ejemplo n.º 6
0
Void MainForm::Sum()
{
	btnTask1->Enabled = false;
	btnTask2->Enabled = false;
	btnTask3->Enabled = false;
	FileStream ^output = gcnew FileStream("sum.txt", FileMode::Create);
	StreamWriter ^writer = gcnew StreamWriter(output);
	String ^str = "";
	int l = 0, m = (primes[primes->Length - 1] / 2 - 1) / 100 + 1;
	pbRun->Value = 0;
	double start = 0.0, time = 0.0;
	start = clock();
	for (int i = 4; i < primes[primes->Length - 1] + 1; i += 2) {
		for (int j = 0; j < count; j++) {
			if (a[i - primes[j]]) {
				str = i.ToString() + " = " + primes[j].ToString() + " + " + (i - primes[j]).ToString();
				writer->WriteLine(str);
				if (l % m == 0) {
					pbRun->Value++;
				}
				l++;
				break;
			}
		}
	}
	time = clock() - start;
	MessageBox::Show("¬рем¤ выполнени¤: " + time.ToString() + " мс");
	pbRun->Value = 0;
	writer->Close();
	output->Close();
	pbRun->Value = 0;
	btnTask1->Enabled = true;
	btnTask2->Enabled = true;
	btnTask3->Enabled = true;
}
void ParseGameHashLibraryFromFile(std::map<std::string, GameID>& GameHashLibraryOut)
{
	SetCurrentDirectory(NativeStr(g_sHomeDir).c_str());
	FILE* pf = NULL;
	fopen_s(&pf, RA_GAME_HASH_FILENAME, "rb");
	if (pf != NULL)
	{
		Document doc;
		doc.ParseStream(FileStream(pf));

		if (!doc.HasParseError() && doc.HasMember("Success") && doc["Success"].GetBool() && doc.HasMember("MD5List"))
		{
			const Value& List = doc["MD5List"];
			for (Value::ConstMemberIterator iter = List.MemberBegin(); iter != List.MemberEnd(); ++iter)
			{
				if (iter->name.IsNull() || iter->value.IsNull())
					continue;

				const std::string sMD5 = iter->name.GetString();
				//GameID nID = static_cast<GameID>( std::strtoul( iter->value.GetString(), NULL, 10 ) );	//	MUST BE STRING, then converted to uint. Keys are strings ONLY
				GameID nID = static_cast<GameID>(iter->value.GetUint());
				GameHashLibraryOut[sMD5] = nID;
			}
		}

		fclose(pf);
	}
}
Ejemplo n.º 8
0
 bool check_file_path(sint32 pathId)
 {
     const utf8 * path = get_file_path(pathId);
     switch (pathId) {
     case PATH_ID_G1:
         if (!File::Exists(path))
         {
             Console::Error::WriteLine("Unable to find '%s'", path);
             return false;
         }
         break;
     case PATH_ID_CUSTOM1:
     case PATH_ID_CUSTOM2:
         if (File::Exists(path))
         {
             try
             {
                 auto fs = FileStream(path, FILE_MODE_OPEN);
                 sint32 index = 36 + (pathId - PATH_ID_CUSTOM1);
                 gRideMusicInfoList[index]->length = fs.GetLength();
             }
             catch (const Exception &)
             {
             }
         }
         break;
     }
     return true;
 }
void ParseGameTitlesFromFile(std::map<GameID, std::string>& GameTitlesListOut)
{
	SetCurrentDirectory(NativeStr(g_sHomeDir).c_str());
	FILE* pf = nullptr;
	fopen_s(&pf, RA_TITLES_FILENAME, "rb");
	if (pf != nullptr)
	{
		Document doc;
		doc.ParseStream(FileStream(pf));

		if (!doc.HasParseError() && doc.HasMember("Success") && doc["Success"].GetBool() && doc.HasMember("Response"))
		{
			const Value& List = doc["Response"];
			for (Value::ConstMemberIterator iter = List.MemberBegin(); iter != List.MemberEnd(); ++iter)
			{
				if (iter->name.IsNull() || iter->value.IsNull())
					continue;

				GameID nID = static_cast<GameID>(std::strtoul(iter->name.GetString(), nullptr, 10));	//	KEYS ARE STRINGS, must convert afterwards!
				const std::string sTitle = iter->value.GetString();
				GameTitlesListOut[nID] = sTitle;
			}
		}

		fclose(pf);
	}
}
Ejemplo n.º 10
0
bool tabtoh::read_entire_file(const QString &filename, QStringList &contents){
    bool err = 0;
    QString currentline;

    QFile file(filename);
    err = file.open(QIODevice::ReadOnly|QIODevice::Text);
    if(err){
        err = 1;
        QTextStream FileStream(&file);
        while(!FileStream.atEnd()){
            currentline = FileStream.readLine();
            //Exclude comments
            if(currentline.contains("#")){
                int ind = currentline.indexOf("#");
                ind = currentline.size() - ind;
                currentline.chop(ind);
            }

            //Replace zero-length line with a newline
            if(currentline.size()){
                contents << currentline;
            }
            else{
                contents << "\r\n";
            }
        }
        file.close();
    }
    else{
        qDebug()<<"(tabtoh) ERROR: cannot open: "<<filename<<"!";
    }

    return err;
}
Ejemplo n.º 11
0
    void LoadScores()
    {
        std::string path = _env->GetFilePath(PATHID::SCORES);
        if (!platform_file_exists(path.c_str()))
        {
            return;
        }

        try
        {
            auto fs = FileStream(path, FILE_MODE_OPEN);
            uint32 fileVersion = fs.ReadValue<uint32>();
            if (fileVersion != 1)
            {
                Console::Error::WriteLine("Invalid or incompatible highscores file.");
                return;
            }

            ClearHighscores();

            uint32 numHighscores = fs.ReadValue<uint32>();
            for (uint32 i = 0; i < numHighscores; i++)
            {
                scenario_highscore_entry * highscore = InsertHighscore();
                highscore->fileName = fs.ReadString();
                highscore->name = fs.ReadString();
                highscore->company_value = fs.ReadValue<money32>();
                highscore->timestamp = fs.ReadValue<datetime64>();
            }
        }
        catch (Exception ex)
        {
            Console::Error::WriteLine("Error reading highscores.");
        }
    }
Ejemplo n.º 12
0
// Returns true on error.
static bool format(std::string FileName) {
  FileManager Files((FileSystemOptions()));
  DiagnosticsEngine Diagnostics(
      IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
      new DiagnosticOptions);
  SourceManager Sources(Diagnostics, Files);
  OwningPtr<MemoryBuffer> Code;
  if (error_code ec = MemoryBuffer::getFileOrSTDIN(FileName, Code)) {
    llvm::errs() << ec.message() << "\n";
    return true;
  }
  if (Code->getBufferSize() == 0)
    return true; // Empty files are formatted correctly.
  FileID ID = createInMemoryFile(FileName, Code.get(), Sources, Files);
  std::vector<CharSourceRange> Ranges;
  if (fillRanges(Sources, ID, Code.get(), Ranges))
    return true;

  FormatStyle FormatStyle = getStyle(Style, FileName);
  Lexer Lex(ID, Sources.getBuffer(ID), Sources,
            getFormattingLangOpts(FormatStyle.Standard));
  tooling::Replacements Replaces = reformat(FormatStyle, Lex, Sources, Ranges);
  if (OutputXML) {
    llvm::outs()
        << "<?xml version='1.0'?>\n<replacements xml:space='preserve'>\n";
    for (tooling::Replacements::const_iterator I = Replaces.begin(),
                                               E = Replaces.end();
         I != E; ++I) {
      llvm::outs() << "<replacement "
                   << "offset='" << I->getOffset() << "' "
                   << "length='" << I->getLength() << "'>"
                   << I->getReplacementText() << "</replacement>\n";
    }
    llvm::outs() << "</replacements>\n";
  } else {
    Rewriter Rewrite(Sources, LangOptions());
    tooling::applyAllReplacements(Replaces, Rewrite);
    if (Inplace) {
      if (Replaces.size() == 0)
        return false; // Nothing changed, don't touch the file.

      std::string ErrorInfo;
      llvm::raw_fd_ostream FileStream(FileName.c_str(), ErrorInfo,
                                      llvm::sys::fs::F_Binary);
      if (!ErrorInfo.empty()) {
        llvm::errs() << "Error while writing file: " << ErrorInfo << "\n";
        return true;
      }
      Rewrite.getEditBuffer(ID).write(FileStream);
      FileStream.flush();
    } else {
      if (Cursor.getNumOccurrences() != 0)
        outs() << "{ \"Cursor\": " << tooling::shiftedCodePosition(
                                          Replaces, Cursor) << " }\n";
      Rewrite.getEditBuffer(ID).write(outs());
    }
  }
  return false;
}
Ejemplo n.º 13
0
void EldritchFramework::LoadPrefsConfig() {
  const SimpleString PrefsConfigFilename =
      GetSaveLoadPath() + SimpleString("prefs.cfg");
  if (FileUtil::Exists(PrefsConfigFilename.CStr())) {
    const FileStream PrefsConfigStream =
        FileStream(PrefsConfigFilename.CStr(), FileStream::EFM_Read);
    ConfigManager::Load(PrefsConfigStream);
  }
}
Ejemplo n.º 14
0
/*****************************************************************************
 * Function:	int RdPipeStream (BufFilePtr f)
 *
 * Returns:
 *
 * Purpose:
 *
 *****************************************************************************/
static int
RdPipeStream (BufFilePtr f)
{
    int    left;

    left = fread(f->buffer, 1, BUFFILESIZE, FileStream(f));

    if (left <= 0)
      {
        f->left = 0;
        return BUFFILEEOF;
      }

    clearerr(FileStream(f));
    f->left = left - 1;
    f->bufp = f->buffer + 1;
    return f->buffer[0];
}
Ejemplo n.º 15
0
    bool PngWrite32bpp(sint32 width, sint32 height, const void * pixels, const utf8 * path)
    {
        bool result = false;

        // Setup PNG
        png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, PngError, PngWarning);
        if (png_ptr == nullptr)
        {
            return false;
        }

        png_infop info_ptr = png_create_info_struct(png_ptr);
        if (info_ptr == nullptr)
        {
            png_destroy_write_struct(&png_ptr, (png_infopp)nullptr);
            return false;
        }

        try
        {
            // Open file for writing
            auto fs = FileStream(path, FILE_MODE_WRITE);
            png_set_write_fn(png_ptr, &fs, PngWriteData, PngFlush);

            // Set error handler
            if (setjmp(png_jmpbuf(png_ptr)))
            {
                throw Exception("PNG ERROR");
            }

            // Write header
            png_set_IHDR(
                png_ptr, info_ptr, width, height, 8,
                PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT
            );
            png_write_info(png_ptr, info_ptr);

            // Write pixels
            uint8 * bits = (uint8 *)pixels;
            for (int y = 0; y < height; y++)
            {
                png_write_row(png_ptr, (png_byte *)bits);
                bits += width * 4;
            }

            // Finish
            png_write_end(png_ptr, nullptr);
            result = true;
        }
        catch (Exception)
        {
        }

        png_destroy_write_struct(&png_ptr, &info_ptr);
        return result;
    }
Ejemplo n.º 16
0
/*********************************************************************
 * Procedure: int ClosePipeStream (BufFilePtr f);
 *
 * Returns:
 *
 * Purpose:
 *
 ********************************************************************/
static int
ClosePipeStream (
    BufFilePtr  f,
    int         doClose)
{
    if (doClose)
        pclose(FileStream(f));

    return 1;
}
Ejemplo n.º 17
0
bool TryClassifyFile(const std::string &path, ClassifiedFile * result)
{
    try
    {
        auto fs = FileStream(path, FILE_MODE_OPEN);
        return TryClassifyFile(&fs, result);
    }
    catch (Exception)
    {
        return false;
    }
}
Ejemplo n.º 18
0
Void MainForm::Primes()
{
	btnTask1->Enabled = false;
	btnTask2->Enabled = false;
	btnTask3->Enabled = false;
	pbRun->Value = 0;
	for (int i = 0; i < n; i++) {
		a[i] = true;
	}
	a[0] = a[1] = false;
	int k = 0, m = count / 100 + 1;
	double start = 0.0, time = 0.0;
	start = clock();
	for (int i = 2; k < count; ++i) {
		if (a[i]) {
			k++;
			if (k % m == 0) {
				pbRun->Value++;
			}
			if (i * 1ll * i < n) {
				for (int j = i * i; j < n; j += i) {
					a[j] = false;
				}
			}
		}
	}
	time = clock() - start;
	MessageBox::Show("¬рем¤ выполнени¤: " + time.ToString() + " мс");
	pbRun->Value = 0;
	k = 0;
	FileStream ^output = gcnew FileStream("primes.txt", FileMode::Create);
	StreamWriter ^writer = gcnew StreamWriter(output);
	String ^str = "";
	for (int i = 0; k < count; i++) {
		if (a[i]) {
			primes[k] = i;
			str = (k + 1).ToString() + " : " + i.ToString();
			writer->WriteLine(str);
			k++;
			if (k % m == 0) {
				pbRun->Value++;
			}
		}
	}
	writer->Close();
	output->Close();
	pbRun->Value = 0;
	btnTask1->Enabled = true;
	btnTask2->Enabled = true;
	btnTask3->Enabled = true;
}
Ejemplo n.º 19
0
void Output2FILE::Output(const std::string& msg)
{
    FILE* tstream = TerminalStream();
    FILE *fstream = FileStream();
    if (!tstream)
        return;
    fprintf(tstream, "%s", msg.c_str());
    fflush(tstream);

    if (fstream != NULL) {
      fprintf(fstream, "%s", msg.c_str());
      fflush(fstream);
    }
}
Ejemplo n.º 20
0
/*virtual*/ void Framework3D::ShutDown()
{
	XTRACE_FUNCTION;

	m_IsShuttingDown = true;

	PRINTF( "Shutting down framework\n" );

#if UPLOADLOG
	STATICHASH( Framework );
	STATICHASH( SendLogsOnQuit );
	if( ConfigManager::GetBool( sSendLogsOnQuit, false, sFramework ) )
	{
		ExceptionUploadLog::UploadLog();
	}
#endif

#if BUILD_WINDOWS
	Console::DeleteInstance();
#endif

	SafeDelete( m_Display );
	SafeDelete( m_SplashWindow );
	SafeDelete( m_Clock );
	SafeDelete( m_Keyboard );
	SafeDelete( m_Mouse );
	SafeDelete( m_AudioSystem );
	SafeDelete( m_UIManager );
	SafeDelete( m_UIInputMap );

	SafeDelete( m_TargetManager );
	SafeDelete( m_Renderer );
	SafeDelete( m_Window );			// Destroy after renderer, else I get GL errors with SDL.

	StringManager::DeleteInstance();
	PrintManager::DeleteInstance();
	ConfigManager::DeleteInstance();

#if DO_PROFILING
	Profiler::GetInstance()->Dump( FileStream( "profiler.txt", FileStream::EFM_Write ) );
	Profiler::DeleteInstance();
#endif

#if BUILD_SDL
	SDL_Quit();
#endif

	m_IsShuttingDown = false;
}
Ejemplo n.º 21
0
void FrameworkUtil::LoadConfigFiles()
{
	STATICHASH( PackageFile );
	STATICHASH( NumConfigFiles );

	// Must load defaults and initialize the package before we can access any other files
	if( !FileUtil::Exists( "Config/default.cfg" ) )
	{
		return;
	}

	ConfigManager::Load( FileStream( "Config/default.cfg", FileStream::EFM_Read ) );

	// Load user variables over the defaults if possible
	if( FileUtil::Exists( "Config/user.cfg" ) )
	{
		ConfigManager::Load( FileStream( "Config/user.cfg", FileStream::EFM_Read ) );
	}

	// Initialize the packstream from whatever the default.cfg specifies.
	PackStream::StaticAddPackageFile( ConfigManager::GetString( sPackageFile ) );

	InternalLoadConfigFiles();
}
Ejemplo n.º 22
0
int FilePacker::PackFile( const char* InFilename, const char* PackFilename, bool Compress )
{
	m_InFileSize = FileUtil::Size( InFilename );

	ReadInFile( FileStream( InFilename, FileStream::EFM_Read ) );

	if( FileUtil::Exists( PackFilename ) )
	{
		ReadPackFile( FileStream( PackFilename, FileStream::EFM_Read ) );
	}
	else
	{
		m_Header.m_MagicID = 'KPCD';
		m_Header.m_NumFiles = 0;
		m_Header.m_OffsetToFiles = 0;	// Fix up just before writing
		m_Header.m_FilesSize = 0;
	}

	AddInFile( InFilename, Compress );

	WritePackFile( FileStream( PackFilename, FileStream::EFM_Write ) );

	return 0;
}
Ejemplo n.º 23
0
void Dlg_MemBookmark::ImportFromFile( std::string sFilename )
{
	FILE* pFile = nullptr;
	errno_t nErr = fopen_s( &pFile, sFilename.c_str(), "r" );
	if ( pFile != nullptr )
	{
		Document doc;
		doc.ParseStream( FileStream( pFile ) );
		if ( !doc.HasParseError() )
		{
			if ( doc.HasMember( "Bookmarks" ) )
			{
				ClearAllBookmarks();

				const Value& BookmarksData = doc[ "Bookmarks" ];
				for ( SizeType i = 0; i < BookmarksData.Size(); ++i )
				{
					MemBookmark* NewBookmark = new MemBookmark();

					wchar_t buffer[ 256 ];
					swprintf_s ( buffer, 256, L"%s", Widen( BookmarksData[ i ][ "Description" ].GetString() ).c_str() );
					NewBookmark->SetDescription ( buffer );

					NewBookmark->SetAddress( BookmarksData[ i ][ "Address" ].GetUint() );
					NewBookmark->SetType( BookmarksData[ i ][ "Type" ].GetInt() );
					NewBookmark->SetDecimal( BookmarksData[ i ][ "Decimal" ].GetBool() );

					NewBookmark->SetValue( GetMemory( NewBookmark->Address(), NewBookmark->Type() ) );
					NewBookmark->SetPrevious ( NewBookmark->Value() );

					AddBookmark ( NewBookmark );
					AddBookmarkMap( NewBookmark );
				}

				if ( m_vBookmarks.size() > 0 )
					PopulateList();
			}
			else
			{
				ASSERT ( " !Invalid Bookmark File..." );
				MessageBox( nullptr, _T("Could not load properly. Invalid Bookmark file."), _T("Error"), MB_OK | MB_ICONERROR );
				return;
			}
		}

		fclose( pFile );
	}
}
Ejemplo n.º 24
0
static std::vector<uint8_t> ReadScriptFile(const utf8* path)
{
    std::vector<uint8_t> result;
    try
    {
        auto fs = FileStream(path, FILE_MODE_OPEN);
        auto size = (size_t)fs.GetLength();
        result.resize(size);
        fs.Read(result.data(), size);
    }
    catch (const std::exception&)
    {
        result.clear();
        result.shrink_to_fit();
    }
    return result;
}
Ejemplo n.º 25
0
int RefactoringTool::saveRewrittenFiles(Rewriter &Rewrite) {
  for (Rewriter::buffer_iterator I = Rewrite.buffer_begin(),
                                 E = Rewrite.buffer_end();
       I != E; ++I) {
    // FIXME: This code is copied from the FixItRewriter.cpp - I think it should
    // go into directly into Rewriter (there we also have the Diagnostics to
    // handle the error cases better).
    const FileEntry *Entry =
        Rewrite.getSourceMgr().getFileEntryForID(I->first);
    std::string ErrorInfo;
    llvm::raw_fd_ostream FileStream(Entry->getName(), ErrorInfo,
                                    llvm::sys::fs::F_Binary);
    if (!ErrorInfo.empty())
      return 1;
    I->second.write(FileStream);
    FileStream.flush();
  }
  return 0;
}
Ejemplo n.º 26
0
bool tabtoh::write_entire_file(QString &filename, QStringList &contents){
    bool err = 0;

    QFile file(filename);
    err = file.open(QIODevice::WriteOnly | QIODevice::Text);
    if(err){
        err = 1;
        QTextStream FileStream(&file);
        for(qint32 i = 0; i < contents.size(); i++){
            FileStream << contents.at(i);
        }

        file.close();
    }
    else{
        qDebug()<<"(tabtoh) ERROR: cannot write to: "<<filename<<"!";
    }

    return err;
}
void ParseMyProgressFromFile(std::map<GameID, std::string>& GameProgressOut)
{
	FILE* pf = nullptr;
	fopen_s(&pf, RA_MY_PROGRESS_FILENAME, "rb");
	if (pf != nullptr)
	{
		Document doc;
		doc.ParseStream(FileStream(pf));

		if (!doc.HasParseError() && doc.HasMember("Success") && doc["Success"].GetBool() && doc.HasMember("Response"))
		{
			//{"ID":"7","NumAch":"14","Earned":"10","HCEarned":"0"},

			const Value& List = doc["Response"];
			for (Value::ConstMemberIterator iter = List.MemberBegin(); iter != List.MemberEnd(); ++iter)
			{
				GameID nID = static_cast<GameID>(std::strtoul(iter->name.GetString(), nullptr, 10));	//	KEYS MUST BE STRINGS
				const unsigned int nNumAchievements = iter->value["NumAch"].GetUint();
				const unsigned int nEarned = iter->value["Earned"].GetUint();
				const unsigned int nEarnedHardcore = iter->value["HCEarned"].GetUint();

				std::stringstream sstr;
				sstr << nEarned;
				if (nEarnedHardcore > 0)
					sstr << " (" << std::to_string(nEarnedHardcore) << ")";
				sstr << " / " << nNumAchievements;
				if (nNumAchievements > 0)
				{
					const int nNumEarnedTotal = nEarned + nEarnedHardcore;
					char bufPct[256];
					sprintf_s(bufPct, 256, " (%1.1f%%)", (nNumEarnedTotal / static_cast<float>(nNumAchievements)) * 100.0f);
					sstr << bufPct;
				}

				GameProgressOut[nID] = sstr.str();
			}
		}

		fclose(pf);
	}
}
Ejemplo n.º 28
0
static void * ReadScriptFile(const utf8 * path, size_t * outSize)
{
    void * buffer = nullptr;
    size_t size = 0;
    try
    {
        auto fs = FileStream(path, FILE_MODE_OPEN);
        size = (size_t)fs.GetLength();
        buffer = Memory::Allocate<void>(size);
        fs.Read(buffer, size);
    }
    catch (Exception)
    {
        Memory::Free(buffer);
        buffer = nullptr;
        size = 0;
    }

    *outSize = size;
    return buffer;
}
Ejemplo n.º 29
0
    /**
     *
     *  rct2: 0x00678998
     */
    bool gfx_load_g1()
    {
        log_verbose("gfx_load_g1()");
        try
        {
            auto fs = FileStream(get_file_path(PATH_ID_G1), FILE_MODE_OPEN);
            rct_g1_header header = fs.ReadValue<rct_g1_header>();

            /* number of elements is stored in g1.dat, but because the entry
             * headers are static, this can't be variable until made into a
             * dynamic array.
             */
            header.num_entries = 29294;

            // Read element headers
#ifdef NO_RCT2
            g1Elements = Memory::AllocateArray<rct_g1_element>(324206);
#endif
            read_and_convert_gxdat(&fs, header.num_entries, g1Elements);

            // Read element data
            _g1Buffer = fs.ReadArray<uint8>(header.total_size);

            // Fix entry data offsets
            for (uint32 i = 0; i < header.num_entries; i++)
            {
                g1Elements[i].offset += (uintptr_t)_g1Buffer;
            }
            return true;
        }
        catch (const Exception &)
        {
            log_fatal("Unable to load g1 graphics");
            if (!gOpenRCT2Headless)
            {
                platform_show_messagebox("Unable to load g1.dat. Your RollerCoaster Tycoon 2 path may be incorrectly set.");
            }
            return false;
        }
    }
Ejemplo n.º 30
0
 void SaveHighscores()
 {
     std::string path = _env->GetFilePath(PATHID::SCORES);
     try
     {
         auto fs = FileStream(path, FILE_MODE_WRITE);
         fs.WriteValue<uint32>(HighscoreFileVersion);
         fs.WriteValue<uint32>((uint32)_highscores.size());
         for (size_t i = 0; i < _highscores.size(); i++)
         {
             const scenario_highscore_entry * highscore = _highscores[i];
             fs.WriteString(highscore->fileName);
             fs.WriteString(highscore->name);
             fs.WriteValue(highscore->company_value);
             fs.WriteValue(highscore->timestamp);
         }
     }
     catch (Exception ex)
     {
         Console::Error::WriteLine("Unable to save highscores to '%s'", path.c_str());
     }
 }