static int IsDATNewer (char *IniFile, char *DatFile) { int ihandle, dhandle, result; struct ftime itime, dtime; ihandle = open (IniFile, O_RDONLY); if (ihandle == -1) return FALSE; dhandle = open (DatFile, O_RDONLY); if (dhandle == -1) { close (ihandle); return FALSE; } if (getftime (ihandle, &itime) == -1) return CloseFiles (ihandle, dhandle); if (getftime (dhandle, &dtime) == -1) return CloseFiles (ihandle, dhandle); if (dtime.ft_year > itime.ft_year) result = TRUE; else if (dtime.ft_year < itime.ft_year) result = FALSE; else if (dtime.ft_month > itime.ft_month) result = TRUE; else if (dtime.ft_month < itime.ft_month) result = FALSE; else if (dtime.ft_day > itime.ft_day) result = TRUE; else if (dtime.ft_day < itime.ft_day) result = FALSE; else if (dtime.ft_hour > itime.ft_hour) result = TRUE; else if (dtime.ft_hour < itime.ft_hour) result = FALSE; else if (dtime.ft_min > itime.ft_min) result = TRUE; else if (dtime.ft_min < itime.ft_min) result = FALSE; else if (dtime.ft_tsec > itime.ft_tsec) result = TRUE; else result = FALSE; CloseFiles (ihandle, dhandle); return result; }
main(int argc, Char *argv[]) { /* ---- Main program ------------------------ */ PASCAL_MAIN(argc, argv); strcpy(this_version, version); strcpy(this_version_date, version_date); printf("==> This is M-Tx %s (Music from TeXt) %s\n", version, version_date); mtxLevel(version); OpenFiles(); no_commands_yet = true; preambleDefaults(); no_report_errors = false; topOfPMXfile(); do { readParagraph(P, orig_line_no, ¶_len); control_paragraph = isControlParagraph(P, para_len); if (control_paragraph) { augmentPreamble(no_report_errors); no_report_errors = true; if (para_len == 0) error("No music paragraphs!", !print); } } while (control_paragraph); doPreamble(); doMusic(); if (!pmx_preamble_done) error("No music paragraphs!", !print); putLine("% Coded by M-Tx"); CloseFiles(); printf("PrePMX done. Now run PMX.\n"); _Escape(0); exit(EXIT_SUCCESS); }
static BROTLI_BOOL DecompressFiles(Context* context) { while (NextFile(context)) { BROTLI_BOOL is_ok = BROTLI_TRUE; BrotliDecoderState* s = BrotliDecoderCreateInstance(BrotliAllocFunc, BrotliFreeFunc, &scratch_buffer_size); if (!s) { fprintf(stderr, "out of memory\n"); return BROTLI_FALSE; } /* This allows decoding "large-window" streams. Though it creates fragmentation (new builds decode streams that old builds don't), it is better from used experience perspective. */ BrotliDecoderSetParameter(s, BROTLI_DECODER_PARAM_LARGE_WINDOW, 1u); is_ok = OpenFiles(context); if (is_ok && !context->current_input_path && !context->force_overwrite && isatty(STDIN_FILENO)) { fprintf(stderr, "Use -h help. Use -f to force input from a terminal.\n"); is_ok = BROTLI_FALSE; } if (is_ok) is_ok = DecompressFile(context, s); BrotliDecoderDestroyInstance(s); if (!CloseFiles(context, is_ok)) is_ok = BROTLI_FALSE; if (!is_ok) return BROTLI_FALSE; } return BROTLI_TRUE; }
int Compiler::main2(int argc, char **argv) { uctran_off = 0; optimize =1; exceptions=1; dfs.printf("c64 starting...\r\n"); while(--argc) { if( **++argv == '-') options(*argv); else { if (PreprocessFile(*argv) == -1) break; if( openfiles(*argv)) { lineno = 0; initsym(); lstackptr = 0; lastst = 0; NextToken(); compile(); summary(); // MBlk::ReleaseAll(); // ReleaseGlobalMemory(); CloseFiles(); } } } //getchar(); return 0; }
bool C4GraphicsResource::ReloadResolutionDependantFiles() { if(!fInitialized) return false; // reload any files that depend on the current resolution // reloads the cursor // Re-open the graphics files if they are not open anymore -- this // happens when the game is running. // Note also that at the moment there are no resolution dependent // graphics files... const bool hadGroupsRegistered = (idRegisteredMainGroupSetFiles != -1); if(!hadGroupsRegistered) { RegisterGlobalGraphics(); RegisterMainGroups(); } fctMouseCursor.idSourceGroup = 0; const bool result = true; if(!hadGroupsRegistered) CloseFiles(); return result; }
void OpenFiles(void) { HRESULT hr; // Display a custom file selection dialog to get both filenames DialogBox(ghInst, MAKEINTRESOURCE(IDD_DIALOG_FILES), ghApp, (DLGPROC) FilesDlgProc); // If user clicked OK, then open the files if (g_bFilesSelected) { g_bFilesSelected = FALSE; // Initialize the global strParam structure with default values InitStreamParams(); // Initialize DirectShow, render the files, and play the streams hr = BlendVideo(g_szFile1, g_szFile2); // If we couldn't play the streams, clean up if (FAILED(hr)) { CloseFiles(); return; } // Set video position, size, and alpha values UpdatePinPos(0); UpdatePinPos(1); UpdatePinAlpha(0); UpdatePinAlpha(1); } }
void PottsMeshReader<SPACE_DIM>::Reset() { CloseFiles(); OpenFiles(); ReadHeaders(); mNodesRead = 0; mElementsRead = 0; }
void C4GraphicsResource::Clear() { fInitialized = false; sfcControl.Clear(); idSfcControl = 0; sfcClonkSkins.Clear(); idSfcClonkSkins = 0; fctCrewClr.Clear(); fctFlagClr.Clear(); fctPlayerClr.Clear(); fctPlayer.Clear(); fctFlag.Clear(); fctCrew.Clear(); fctWealth.Clear(); fctRank.Clear(); fctFire.Clear(); fctBackground.Clear(); fctCaptain.Clear(); fctMouseCursor.Clear(); fctSelectMark.Clear(); fctMenu.Clear(); fctUpperBoard.Clear(); fctLogo.Clear(); fctConstruction.Clear(); fctEnergy.Clear(); fctOptions.Clear(); fctArrow.Clear(); fctExit.Clear(); fctHand.Clear(); fctGamepad.Clear(); fctBuild.Clear(); // GUI data sfcCaption.Clear(); sfcButton.Clear(); sfcButtonD.Clear(); sfcScroll.Clear(); sfcContext.Clear(); idSfcCaption = idSfcButton = idSfcButtonD = idSfcScroll = idSfcContext = 0; barCaption.Clear(); barButton.Clear(); barButtonD.Clear(); fctButtonHighlight.Clear(); fctIcons.Clear(); fctIconsEx.Clear(); fctButtonHighlightRound.Clear(); fctSubmenu.Clear(); fctCheckbox.Clear(); fctBigArrows.Clear(); fctProgressBar.Clear(); fctContext.Default(); // unhook deflist from font FontRegular.SetCustomImages(NULL); Achievements.Clear(); // closing the group set will also close the graphics.ocg // this is just for games that failed to init // normally, this is done after successful init anyway CloseFiles(); }
void PlayListItemESEQ::LoadFiles() { CloseFiles(); if (wxFile::Exists(_ESEQFileName)) { _ESEQFile = new ESEQFile(); _ESEQFile->Load(_ESEQFileName); } }
static void quit_avery(RDArsrc *m) { CloseFiles(m); CLSNRD(FileNumber); if(m!=NULL) { killwindow(m); free_rsrc(m); } ShutdownSubsystems(); }
static BROTLI_BOOL CompressFiles(Context* context) { while (NextFile(context)) { BROTLI_BOOL is_ok = BROTLI_TRUE; BrotliEncoderState* s = BrotliEncoderCreateInstance(NULL, NULL, NULL); if (!s) { fprintf(stderr, "out of memory\n"); return BROTLI_FALSE; } BrotliEncoderSetParameter(s, BROTLI_PARAM_QUALITY, (uint32_t)context->quality); if (context->lgwin > 0) { /* Specified by user. */ /* Do not enable "large-window" extension, if not required. */ if (context->lgwin > BROTLI_MAX_WINDOW_BITS) { BrotliEncoderSetParameter(s, BROTLI_PARAM_LARGE_WINDOW, 1u); } BrotliEncoderSetParameter(s, BROTLI_PARAM_LGWIN, (uint32_t)context->lgwin); } else { /* 0, or not specified by user; could be chosen by compressor. */ uint32_t lgwin = DEFAULT_LGWIN; /* Use file size to limit lgwin. */ if (context->input_file_length >= 0) { int32_t size = 1 << BROTLI_MIN_WINDOW_BITS; lgwin = BROTLI_MIN_WINDOW_BITS; while (size < context->input_file_length) { size <<= 1; lgwin++; if (lgwin == BROTLI_MAX_WINDOW_BITS) break; } } BrotliEncoderSetParameter(s, BROTLI_PARAM_LGWIN, lgwin); } if (context->input_file_length > 0) { uint32_t size_hint = context->input_file_length < (1 << 30) ? (uint32_t)context->input_file_length : (1u << 30); BrotliEncoderSetParameter(s, BROTLI_PARAM_SIZE_HINT, size_hint); } is_ok = OpenFiles(context); if (is_ok && !context->current_output_path && !context->force_overwrite && isatty(STDOUT_FILENO)) { fprintf(stderr, "Use -h help. Use -f to force output to a terminal.\n"); is_ok = BROTLI_FALSE; } if (is_ok) is_ok = CompressFile(context, s); BrotliEncoderDestroyInstance(s); if (!CloseFiles(context, is_ok)) is_ok = BROTLI_FALSE; if (!is_ok) return BROTLI_FALSE; } return BROTLI_TRUE; }
BOOL CNamedIndexesOptimiser::Optimise(void) { int i; CNamedIndexesBlocks* pcBlocks; CIndexedFile* pcIndexedFile; TRISTATE tTotalResult; BOOL bResult; ReturnOnFalse(OpenFiles()); AssignBlockNumbers(); tTotalResult = TRIFALSE; for (i = 0; i < mpacBlocks->NumElements(); i++) { pcBlocks = mpacBlocks->Get(i); pcIndexedFile = GetFile(pcBlocks->GetDataSize(), pcBlocks->GetFileNumber()); bResult = OptimiseBlock(pcBlocks, pcIndexedFile); if (!bResult) { return CloseFiles(FALSE); } } return CloseFiles(TRUE); }
void Fini( void ) { freeSectionList( &Sections ); freeLabelList( 0 ); ORLFileScan( ObjFileHnd, NULL, &SectionFini ); if( Options & PRINT_PUBLICS ) { freePublics(); } FreeHashTables(); FreeServicesUsed(); CloseFiles(); MemPrtList(); MemClose(); MsgFini(); }
void TrianglesMeshReader<ELEMENT_DIM, SPACE_DIM>::Reset() { CloseFiles(); mNodesRead = 0; mElementsRead = 0; mFacesRead = 0; mBoundaryFacesRead = 0; mCableElementsRead = 0; mNclItemsRead = 0; mEofException = false; OpenFiles(); ReadHeaders(); }
// OpenFiles(): // Tests to make sure the paths are valid and opens the files. // This also generates an output and ubernull name if none are // specified. Returns an error if something went wrong. // You should call GenerateNames() before calling this function. // Overload me if you need to open more files. int CLIFileManipBase::OpenFiles() { // See if the source and output names are the same if( stricmp( source_name, output_name ) == 0 ) return CLIFILEMANIPBASE_SAME_SOURCE_AND_OUTPUT; // Open the Source File int error = OpenSource(); if( error != CLIFILEMANIPBASE_OK ) return error; // Open the Output File error = OpenOutput(); if( error != CLIFILEMANIPBASE_OK ) { CloseFiles(); return error; } return CLIFILEMANIPBASE_OK; }
int CompareFiles( void ) /**********************/ { int error; int result; WResFileID fileid1; WResFileID fileid2; error = OpenFiles( &fileid1, &fileid2 ); if (!error) { result = CompareContents( fileid1, fileid2 ); } else { result = -1; } CloseFiles( fileid1, fileid2 ); return( result ); }
// OpenFiles(): // Tests to make sure the paths are valid and opens the files. // This also generates an output and ubernull name if none are // specified. Returns an error if something went wrong. int Populate::OpenFiles() { GenerateNames( "-Populated" ); // Open the LWO File, if needed if( use_lwo ) { _lwo = new bifstream( lwo_name, ios::nocreate ); if( !(*_lwo) ) { CloseFiles(); return POPULATE_CANT_OPEN_LWO; } _lwo->SetEndian( ENDIAN_MOTOROLA ); } int error = CLIFileManipBase::OpenFiles(); if( error != POPULATE_OK ) return error; // Test the file headers (only happens if the input files were opened OK) char header[4]; if( _in != NULL ) { // Test the LWS header _in->read( header, 4 ); if( strncmp( header, "LWSC", 4 ) != 0 ) return POPULATE_SOURCE_ISNT_LWS; _in->seekg( 0, ios::beg ); } if( _lwo != NULL ) { // Test the LWO header if( use_lwo ) { _lwo->seekg( 8, ios::beg ); _lwo->read( header, 4 ); if( strncmp( header, "LWOB", 4 ) != 0 ) return POPULATE_OBJECT_ISNT_LWO; _lwo->seekg( 0, ios::beg ); } } return POPULATE_OK; }
int CopyFile( const char * file1, const char * file2 ) /****************************************************/ { size_t len; auto struct stat statblk; auto struct utimbuf utimebuf; remove( file2 ); OutFile = NOFILE; InFile = QOpen( file1, O_RDONLY | O_BINARY, 0 ); OutFile = QOpen( file2, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0 ); while( (len = QRead( InFile, InputBuffer, MAX_OBJECT_REC_SIZE )) != 0 ) { QWrite( OutFile, InputBuffer, len ); } CloseFiles(); if( stat( file1, &statblk ) == 0 ) { utimebuf.actime = statblk.st_atime; utimebuf.modtime = statblk.st_mtime; utime( file2, &utimebuf ); } return( OK ); }
static void ProcFile( char * fname ) /**********************************/ { int ftype; char * name; int status; int namelen; char * bak; namelen = strlen( fname ) + 5; name = alloca( namelen ); if( name == NULL ) Suicide(); // null == no stack space left. strcpy( name, fname ); ReplaceExt( name, ".obj", FALSE ); InFile = QOpen( name, O_RDONLY | O_BINARY, 0 ); for(;;) { CleanRecStuff(); ftype = ReadRec(); if( ftype == ENDLIBRARY || ftype == ENDFILE ) { break; } else if( ftype == LIBRARY ) { Warning( "exclude option does not apply to libraries" ); FreeList( ExcludeList ); ExcludeList = NULL; } else if( ftype != OBJECT ) { Error( "file is not a standard OBJECT or LIBRARY file" ); } OutFile = QOpen( TEMP_OBJ_NAME, O_WRONLY|O_CREAT|O_TRUNC|O_BINARY, 0 ); do { ProcessRec(); status = ReadRec(); } while( status == OK ); if( status == ENDMODULE ) { ProcessRec(); // process the modend rec. DoReplace(); } else { Error( "premature end of file encountered" ); } FreeList( ExcludeList ); // do this here so concatenated .obj files ExcludeList = NULL; // only have the first module excluded. } CloseFiles(); if( MakeBackup ) { bak = alloca( namelen ); if( bak == NULL ) Suicide(); // null == no stack space left. strcpy( bak, name ); if( ftype == ENDLIBRARY ) { ReplaceExt( bak, ".bak", TRUE ); } else { ReplaceExt( bak, ".bob", TRUE ); } CopyFile( name, bak ); } QRemove( name ); if( ftype == ENDLIBRARY ) { rename( TEMP_LIB_NAME, name ); } else { rename( TEMP_OBJ_NAME, name ); } FileCleanup(); }
void Init( void ) { char cmd_line[ CMD_LINE_LEN ]; return_val error; char **list; OutputDest = STDOUT_FILENO; ChangePrintDest( OutputDest ); relocSections.first = NULL; relocSections.last = NULL; if( !MsgInit() ) { // MsgInit does its own error message printing exit( -1 ); } MemOpen(); getcmd( cmd_line ); HandleArgs( cmd_line ); openFiles(); initGlobals(); error = initHashTables(); if( error == OKAY ) { error = initServicesUsed(); if( error == OKAY ) { error = initSectionTables(); if( error != OKAY ) { // free hash tables and services MemClose(); LeaveProgram( error, WHERE_CREATE_SEC_TABLES ); } } else { // free hash tables CloseFiles(); FreeHashTables(); // initServicesUsed does its own error message printing exit( error ); } } else { CloseFiles(); MemClose(); LeaveProgram( error, WHERE_INIT_HASH_TABLES ); } if( Options & PRINT_PUBLICS ) { CreatePublicsArray(); } if( IsMasmOutput() ) { CommentString = MASM_COMMENT_STRING; } if( IsIntelx86() ) { SkipRefTable = HashTableCreate( RECOGNITION_TABLE_SIZE, HASH_STRING, (hash_table_comparison_func) stricmp ); if( SkipRefTable ) { list = intelSkipRefList; while( *list ) { error = HashTableInsert( SkipRefTable, (hash_value) *list, (hash_data) *list ); if( error != OKAY ) break; list++; } } } if( !LabelChar ) { if( IsMasmOutput() ) { LabelChar = 'L'; } else { LabelChar = 'X'; } } }
UINT COXFileChanger::Run() // --- In : // --- Out : // --- Returns : occurences of found match or replacement // --- Effect : perform search/replace { int M = PtrToInt(m_pSearch->GetSize()); // ... search text/binary length int M_1 = M - 1; // ... array max subscript int MM_1 = M + M_1; // ... i shift value when found int n = 0; // ... actual bytes read from the file at one time int i = 0; // ... scanning position pointer of file buffer int j = 0; // ... scanning position pointer of search text/binary int w = 0; // ... write position pointer in the loaded file buffer int t = 0; // ... temp value int skip[255]; // ... skip array for each byte value LONG lPos0 = 0; // ... file position of the current buffer[0] LONG nCurInPos = 0; // ... loading position of the input file LONG nInPos = 0; // ... match found position of the input file LONG nCurOutPos = 0; // ... writing position of the output file LONG nOutPos = 0; // ... replace text/binary position of the output file LONG nChPos = 0; // ... position of prev/next char for whole word match LONG nChPosMax = 0; // ... maximum file position of prev/next char for whole word match UINT nResult = 0; // ... match occurence BYTE* pBuffer = NULL; // ... file buffer BOOL bEOF = FALSE; // ... end of file BOOL bContinue = TRUE; // ... default bContinue value BOOL bReplace = GetFlag(m_nFlagReplace); // ... Replace() (TRUE) or Search() (FALSE) BOOL bText = GetFlag(m_nFlagText); // ... whether text search BOOL bMatchCase = (!bText || GetFlag(m_nFlagMatchCase)); // ... whether case-insensitive BOOL bWholeWord = (bText && GetFlag(m_nFlagWholeWord)); // ... whether whole word char ch = '\0'; // ... prev/next char for whole word match CString sSafeStack; // Increases the stack size if (M == 0) { TRACE0("COXFileChanger::Run(): aborted: zero length search text/binary encountered.\r\n"); return 0; } if (m_nBufferSize < M) { TRACE0("COXFileChanger::Run(): aborted: length of search text/binary exceeds upper limit.\r\n"); return 0; } // Initialize skip array for (j = 0; j < 256; j++) skip[j] = M; for (j = 0, t = M; j < M; j++) skip[m_pSearch->GetAt(j)] = --t; if (!bMatchCase) for (j = 0, t = M; j < M; j++) skip[m_pSearchOppositeCase->GetAt(j)] = --t; try { // Alllocate the buffer pBuffer = new BYTE[m_nBufferSize]; OpenFiles(); nChPosMax = (LONG) m_pFileIn->GetLength() - 1; while (!bEOF && (n = m_pFileIn->Read(pBuffer, m_nBufferSize)) > 0) { bEOF = (n < m_nBufferSize); if (!bContinue && bReplace) { // Cycle until all remaining contents are copied m_pFileOut->Write(pBuffer, n); continue; } if (!bContinue || n < M) break; i = - M; w = 0; while (bContinue) { // search one occurence for (i += MM_1, j = M_1; 0 <= j && i < n; i--, j--) { while (pBuffer[i] != m_pSearch->GetAt(j) && (bMatchCase || pBuffer[i] != m_pSearchOppositeCase->GetAt(j))) { t = skip[pBuffer[i]]; i += __max(M - j, t); if (n <= i) { i++; break; } j = M_1; } } // out of buffer boundary if (n <= i) { if (bReplace) m_pFileOut->Write(pBuffer + w, (bEOF ? n : i - M_1) - w); if (!bEOF) lPos0 = (LONG) m_pFileIn->Seek(i - M_1 - n, CFile::current); break; } i++; nCurInPos = (LONG) m_pFileIn->GetPosition(); nInPos = lPos0 + i; // test wholeword match if (bWholeWord) { nChPos = i - 1; for (t = 0; t < 2; t++) { // look in buffer first if (0 <= nChPos && nChPos < n) ch = *(pBuffer + nChPos); else { // look in the file nChPos += lPos0; if (0 <= nChPos && nChPos <= nChPosMax) { m_pFileIn->Seek(nChPos, CFile::begin); m_pFileIn->Read(&ch, 1); } else // beginning or the end of the file ch = ' '; } if (isalnum(ch)) break; nChPos = i + M; } if (t < 2) { m_pFileIn->Seek(nCurInPos, CFile::begin); i -= M_1; continue; } } // found one match bContinue = GetFlag(m_nFlagAll); m_pFileIn->Seek(nInPos, CFile::begin); if (bReplace) { if (OnPreReplace(m_pFileIn, nInPos, bContinue)) { nResult++; m_pFileOut->Write(pBuffer + w, i - w); nOutPos = (LONG) m_pFileOut->GetPosition(); m_pFileOut->Write(m_pReplace->GetData(), PtrToUint(m_pReplace->GetSize())); w = i + M; nCurOutPos = (LONG) m_pFileOut->GetPosition(); m_pFileOut->Seek(nOutPos, CFile::begin); OnPostReplace(m_pFileOut, nOutPos); m_pFileOut->Seek(nCurOutPos, CFile::begin); } if (!bContinue) m_pFileOut->Write(pBuffer + w, n - w); } else { if (OnFound(m_pFileIn, nInPos, bContinue)) nResult++; } m_pFileIn->Seek(nCurInPos, CFile::begin); } } CloseFiles(); } catch (...) { if (!GetFlag(m_nFlagUseCFile)) { CString sTempFileName = m_pFileOut->GetFilePath(); m_pFileIn->Abort(); m_pFileOut->Abort(); if (bReplace && GetFlag(m_nFlagOverwrite) && !sTempFileName.IsEmpty()) ::DeleteFile(sTempFileName); } m_pFileIn = NULL; m_pFileOut = NULL; delete[] pBuffer; pBuffer = NULL; throw; } // Clean up delete[] pBuffer; pBuffer = NULL; m_pFileIn = NULL; m_pFileOut = NULL; return nResult; }
Result Par2Creator::Process(const CommandLine &commandline) { // Get information from commandline noiselevel = commandline.GetNoiseLevel(); blocksize = commandline.GetBlockSize(); sourceblockcount = commandline.GetBlockCount(); const list<CommandLine::ExtraFile> extrafiles = commandline.GetExtraFiles(); sourcefilecount = (u32)extrafiles.size(); u32 redundancy = commandline.GetRedundancy(); recoveryblockcount = commandline.GetRecoveryBlockCount(); recoveryfilecount = commandline.GetRecoveryFileCount(); firstrecoveryblock = commandline.GetFirstRecoveryBlock(); recoveryfilescheme = commandline.GetRecoveryFileScheme(); string par2filename = commandline.GetParFilename(); size_t memorylimit = commandline.GetMemoryLimit(); largestfilesize = commandline.GetLargestSourceSize(); // Compute block size from block count or vice versa depending on which was // specified on the command line if (!ComputeBlockSizeAndBlockCount(extrafiles)) return eInvalidCommandLineArguments; // Determine how many recovery blocks to create based on the source block // count and the requested level of redundancy. if (redundancy > 0 && !ComputeRecoveryBlockCount(redundancy)) return eInvalidCommandLineArguments; // Determine how much recovery data can be computed on one pass if (!CalculateProcessBlockSize(memorylimit)) return eLogicError; // Determine how many recovery files to create. if (!ComputeRecoveryFileCount()) return eInvalidCommandLineArguments; if (noiselevel > CommandLine::nlQuiet) { // Display information. cout << "Block size: " << blocksize << endl; cout << "Source file count: " << sourcefilecount << endl; cout << "Source block count: " << sourceblockcount << endl; if (redundancy>0 || recoveryblockcount==0) cout << "Redundancy: " << redundancy << '%' << endl; cout << "Recovery block count: " << recoveryblockcount << endl; cout << "Recovery file count: " << recoveryfilecount << endl; cout << endl; } // Open all of the source files, compute the Hashes and CRC values, and store // the results in the file verification and file description packets. if (!OpenSourceFiles(extrafiles)) return eFileIOError; // Create the main packet and determine the setid to use with all packets if (!CreateMainPacket()) return eLogicError; // Create the creator packet. if (!CreateCreatorPacket()) return eLogicError; // Initialise all of the source blocks ready to start reading data from the source files. if (!CreateSourceBlocks()) return eLogicError; // Create all of the output files and allocate all packets to appropriate file offets. if (!InitialiseOutputFiles(par2filename)) return eFileIOError; if (recoveryblockcount > 0) { // Allocate memory buffers for reading and writing data to disk. if (!AllocateBuffers()) return eMemoryError; // Compute the Reed Solomon matrix if (!ComputeRSMatrix()) return eLogicError; // Set the total amount of data to be processed. progress = 0; totaldata = blocksize * sourceblockcount * recoveryblockcount; previouslyReportedFraction = -10000000; // Big negative // Start at an offset of 0 within a block. u64 blockoffset = 0; while (blockoffset < blocksize) // Continue until the end of the block. { // Work out how much data to process this time. size_t blocklength = (size_t)min((u64)chunksize, blocksize-blockoffset); // Read source data, process it through the RS matrix and write it to disk. if (!ProcessData(blockoffset, blocklength)) return eFileIOError; blockoffset += blocklength; } if (noiselevel > CommandLine::nlQuiet) cout << "Writing recovery packets" << endl; // Finish computation of the recovery packets and write the headers to disk. if (!WriteRecoveryPacketHeaders()) return eFileIOError; // Finish computing the full file hash values of the source files if (!FinishFileHashComputation()) return eLogicError; } // Fill in all remaining details in the critical packets. if (!FinishCriticalPackets()) return eLogicError; if (noiselevel > CommandLine::nlQuiet) cout << "Writing verification packets" << endl; // Write all other critical packets to disk. if (!WriteCriticalPackets()) return eFileIOError; // Close all files. if (!CloseFiles()) return eFileIOError; if (noiselevel > CommandLine::nlSilent) cout << "Done" << endl; return eSuccess; }
WriteToFile::~WriteToFile() { CloseFiles(); }
int main(int argc, char ** argv) { void * video_mem = 0; int sprite_fd = 0; int nes_fd = 0; int ret_val = 0; if(InitializeFiles(sprite_fd, nes_fd, video_mem)) { Game game(sprite_fd, nes_fd, video_mem); game.Run(); if(!CloseFiles(sprite_fd, nes_fd, video_mem)) ret_val = 2; } else { ret_val = 1; } // Create the Sprite Engine /*SpriteEngine sprite(sprite_fd, video_mem); NesController nes(nes_fd); // Set Background to green sprite.DrawRectangleBg(0, 0, WIDTH - 1, HEIGHT - 1, 0, 63, 0); // Initialize the background tiles for(int i = 0; i < TILE_ROWS; ++i) { for(int j = 0; j < TILE_COLS; ++j) { tile.x_index = j; tile.y_index = i; tile.mem_slot = (i * TILE_COLS + j); sprite.ClearTileMem(j, i, 12 + i, (i) * 4, i); sprite.UpdateTileAttr(&tile); } } // Initialize player sprite player.disp_index = 0; player.enable = 1; player.mem_slot = 0; player.width = 32; player.height = 32; player.x = 0; player.y = 0; sprite.ClearSpriteMem(player.mem_slot, 31, 10, 25); sprite.UpdateSpriteAttr(&player, SPR_XY_ATTR); sprite.UpdateSpriteAttr(&player, SPR_EMWH_ATTR); while(!nes.Start()) { nes.Update(); if(nes.Right() && player.x < WIDTH) player.x++; if(nes.Left() && player.x > 0) player.x--; if(nes.Up() && player.y > 0) player.y--; if(nes.Down() && player.y < HEIGHT) player.y++; sprite.UpdateSpriteAttr(&player, SPR_XY_ATTR); if(nes.A()) sprite.EnableTiledBg(); else sprite.EnableBufferedBg(); usleep(delay); }*/ return ret_val; }
void CLogManager::AddMessage(E_LOGTYPE _eType, std::string const &sFormat, char const *pFile, int nLine, ...) const { // vfprintf(stderr, format, argptr); std::string sFile = pFile; auto Splitted = StringHelper::Split(sFile, "\\"); auto now = std::time(nullptr); std::shared_ptr<tm> pLocalTime(new tm); localtime_s(pLocalTime.get(), &now); sprintf_s(g_pBuffer, 1024 * 4, "[%02d:%02d:%02d] File: %s\\%s(%d) | ", pLocalTime->tm_hour, pLocalTime->tm_min, pLocalTime->tm_sec, Splitted[Splitted.size() - 2].c_str(), Splitted[Splitted.size() - 1].c_str(), nLine); std::string sFormattedFormat = std::string(g_pBuffer) + sFormat + std::string("\n"); va_list argptr; va_start(argptr, nLine); int n = vsnprintf_s(g_pBuffer, 1024 * 4, 1024 * 4, sFormattedFormat.c_str(), argptr); va_end(argptr); if (_eType == E_LOGTYPE::LOG_ERROR) { if (m_eErrorDest & E_LOGDEST::DEBUG_WINDOW) { OutputDebugStringA(g_pBuffer); } if (m_eErrorDest & E_LOGDEST::SEP_FILE) { fputs(g_pBuffer, m_pErrorFile); } if (m_eErrorDest & E_LOGDEST::INFILE) { fputs(g_pBuffer, m_pLogFile); } if (m_eErrorDest & E_LOGDEST::MSGBOX) { MessageBoxA(0, g_pBuffer, "Error!", MB_OK); } if (m_eErrorDest & E_LOGDEST::STDERR) { fputs(g_pBuffer, stderr); } } else if (_eType == E_LOGTYPE::LOG_WARNING) { if (m_eWarningDest & E_LOGDEST::DEBUG_WINDOW) { OutputDebugStringA(g_pBuffer); } if (m_eWarningDest & E_LOGDEST::SEP_FILE) { fputs(g_pBuffer, m_pWarnFile); } if (m_eWarningDest & E_LOGDEST::INFILE) { fputs(g_pBuffer, m_pLogFile); } if (m_eWarningDest & E_LOGDEST::MSGBOX) { MessageBoxA(0, g_pBuffer, "Warning!", MB_OK); } if (m_eWarningDest & E_LOGDEST::STDERR) { fputs(g_pBuffer, stderr); } } else if (_eType == E_LOGTYPE::LOG_INFO) { if (m_eInfoDest & E_LOGDEST::DEBUG_WINDOW) { OutputDebugStringA(g_pBuffer); } if (m_eInfoDest & E_LOGDEST::SEP_FILE) { fputs(g_pBuffer, m_pInfoFile); } if (m_eInfoDest & E_LOGDEST::INFILE) { fputs(g_pBuffer, m_pLogFile); } if (m_eInfoDest & E_LOGDEST::MSGBOX) { MessageBoxA(0, g_pBuffer, "Info!", MB_OK); } if (m_eInfoDest & E_LOGDEST::STDERR) { fputs(g_pBuffer, stderr); } } CloseFiles(); OpenFiles(); }
~GNUplotObserver() { CloseFiles(); }
void OpenSMOKE_ICEM::Solve() { double timeStart, timeEnd; BzzVector xMin; BzzVector xMax; BzzVector xInitial; PrepareFiles(); ODE_ICEM_Object.assignICEM(this); // 1.A if (iTwoEquationModel == false) { ChangeDimensions(NC+1, &xMin); xMin=ZERO; xMin[NC+1] = 250.; ChangeDimensions(NC+1, &xMax); xMax=ONE; xMax[NC+1] = 6000.; xInitial = omega; xInitial.Append(T); } // 1.B if (iTwoEquationModel == true) { soot2EModel->initial_values(rho); indexTwoEquations = NC+2; ChangeDimensions(NC+3, &xMin); xMin=ZERO; xMin[NC+1] = 250.; ChangeDimensions(NC+3, &xMax); xMax=ONE; xMax[NC+1] = 6000.; xInitial = omega; xInitial.Append(T); xInitial.Append(soot2EModel->phiNStart); xInitial.Append(soot2EModel->phiMStart); } o(xInitial, 0., &ODE_ICEM_Object); o.MyStepPrint(); o.SetMinimumConstraints(xMin); o.SetMaximumConstraints(xMax); if (iRelativeTolerance == true) o.SetTolRel(MachEpsFloat()*relativeTolerance); if (iAbsoluteTolerance == true) o.SetTolAbs(absoluteTolerance); { countGlobalIterations = -1; // From -1 to avoid to store results from the first iteration timeStart = BzzGetCpuTime(); TauTotal = 2.*Constants::pi/rotation_rate * number_of_cycles; o(TauTotal,TauTotal); timeEnd = BzzGetCpuTime(); } if (iVerbose == true) { cout << endl; cout << "Number of function for Jacobian: " << o.GetNumFunctionForJacobian() << endl; cout << "Numerical Jacobians: " << o.GetNumNumericalJacobian() << endl; cout << "Time DAE solution: " << timeEnd - timeStart << " s" << endl << endl; } if (iVerboseSensitivity == true) { } CloseFiles(); }
int main (int argc, char **argv) { struct LinkList ll; struct SetCliques scl; struct LinProg lp; struct Problem prob; int effort; if (argc < 8 || argc > 13) { printf ("Usage: %s <link file> <effort> <output format> <output filename> <random seed> <obj type> <lambda> (<clique input file> <lossFile> <epsilon> <routeFile> <flow LB file>)\n", argv[0]); exit(-1); } // read in problem: i.e. single/multipath and list of sources and destinations readInfo(argv[1], &ll, &prob); // how much effort; effort = atoi(argv[2]); // what output format lp.opform = atoi(argv[3]); // Lili added: by default, no constant variables lp.const_var = 0; // Lili added: by default, no variable lower bounds lp.var_LBs = 0; //Modeified by Yi Li to be consistent with lowerbound //if ((prob.multipath == 0) && (lp.opform != OPFORM_LPSOLVE)) { if ((prob.multipath == 0) && ((lp.opform == OPFORM_MATLAB_SPARSE)||(lp.opform == OPFORM_MATLAB))) { printf ("matlab can not solve single path problem\n"); exit(-1); } if (ll.ifmodel != IFMODEL_PROTO) { printf ("upper bound for physical model not implemented yet\n"); exit(1); } srand(atoi(argv[5])); if (strcmp(argv[8], "NULL") == 0) { // find cliques, making a certain number of attempts findCliques (ll, &scl, effort); prob.clique_const_type = CLIQUE_OPT_SCHEDULE; } else { // read cliques from input file argv[7] readCliques(argv[8], ll, &scl); prob.clique_const_type = CLIQUE_802_11; } //printCliques (scl); // open the files needed for output OpenFiles (&(lp.fp), lp.opform, argv[4]); // generate the linear program prob.obj_type = atoi(argv[6]); prob.lambda = atof(argv[7]); if (argc >= 10) readLoss(argv[9], &ll); if (argc >= 11) prob.epsilon = atof(argv[10]); if (argc >= 12) readRoute(argv[11], prob, ll, &lp); if (argc == 13) readFlowLowerBound(argv[12], prob, ll, &lp); genUpperBoundLinProg (ll, scl, prob, &lp); // close output files CloseFiles (&(lp.fp), lp.opform); return 0; }
CLogManager::~CLogManager() { SAFE_DELETE_ARRAY(g_pBuffer); CloseFiles(); }
void onFinalizedRun() { CloseFiles(); std::ofstream ScriptFile(std::string(m_OutputDir+"/script.gnuplot").c_str()); if (!m_Terminal.empty()) { ScriptFile << "set terminal " << m_Terminal << "\n"; if (!m_Output.empty()) ScriptFile << "set output \"" << m_OutputDir << "/" << m_Output << "\"\n"; } ScriptFile << "set xtics rotate font \",5\"\n"; ScriptFile << "set ytics font \",7\"\n"; ScriptFile << "set xdata time\n"; ScriptFile << "set timefmt \"%Y-%m-%dT%H:%M:%S\"\n"; ScriptFile << "set datafile separator \" \"\n"; ScriptFile << "set datafile commentschars \"#\"\n"; ScriptFile << "set format x \"%Y-%m-%d\\n%H:%M:%S\"\n"; ScriptFile << "set datafile missing \"NaN\"\n"; ScriptFile << "set xlabel \"Time\"\n"; unsigned int Columns = 1; unsigned int Rows = 1; if (m_Graphs.size() > 1) { Columns = (unsigned int)(std::ceil(std::sqrt(m_Graphs.size()))); Rows = (unsigned int)(std::ceil(m_Graphs.size() / Columns)); if (Columns*Rows < m_Graphs.size()) Rows++; } ScriptFile << "set multiplot layout " << Rows << "," << Columns << " rowsfirst scale 1,1\n"; std::map<std::string,GraphInfo>::iterator Git; std::map<std::string,GraphInfo>::iterator Gitb = m_Graphs.begin(); std::map<std::string,GraphInfo>::iterator Gite = m_Graphs.end(); for (Git = Gitb; Git != Gite; ++Git) { ScriptFile << "set title \"" << (*Git).second.Title << "\" font \",10\"\n"; ScriptFile << "set key " << (*Git).second.Key << "\n"; if ((*Git).second.YLabel.empty()) ScriptFile << "unset ylabel\n"; else ScriptFile << "set ylabel \"" << (*Git).second.YLabel << "\"\n"; ScriptFile << "plot "; std::list<SerieInfo*>::iterator Sit; std::list<SerieInfo*>::iterator Sitb = (*Git).second.Series.begin(); std::list<SerieInfo*>::iterator Site = (*Git).second.Series.end(); for (Sit = Sitb; Sit != Site; ++Sit) { std::string SourceDir = m_OutputDir; if ((*Sit)->Type == SerieInfo::SERIE_FILE) SourceDir = m_InputDir; std::string Label = (*Sit)->Label; if (Label.empty()) { if ((*Sit)->Type == SerieInfo::SERIE_FILE) Label = (*Sit)->SourceFile; else { std::string UnitIDStr; openfluid::tools::convertValue((*Sit)->UnitID,&UnitIDStr); Label= (*Sit)->VarName + " (" + (*Sit)->UnitsClass + "#" + UnitIDStr + ")"; } } if (Sit != Sitb) ScriptFile << ", "; ScriptFile << "\"" << SourceDir << "/" << (*Sit)->SourceFile << "\" using 1:2 with " << (*Sit)->Style << " title \"" << Label << "\""; } ScriptFile << "\n"; } ScriptFile << "unset multiplot\n"; ScriptFile.close(); tryOpenGNUplot(); }