void classISQL::SaveSQL() { QMultiLineEdit *txt; QString qsFileName; if ( pTabBar->currentTab() == 0 ) { txt = txtSQL; qsFileName = qsSQLFileName; } else { txt = txtResults; qsFileName = qsResultsFileName; } if ( qsFileName == "" ) { SaveAsSQL(); return; } // TRY TO SAVE THE FILE QFile hFile( qsFileName ); if ( !hFile.open( IO_WriteOnly ) ) return; hFile.writeBlock( txt->text(), txt->text().length() ); hFile.close(); }
void CSourceDataGenerator::SaveCharmap(const CharMap &charmap, bool compress, enum OutputFormat format, const wxString &fileName) { wxFileName fileNameInfo(fileName, wxPATH_NATIVE); wxString hFilePath, cFilePath; if (fileNameInfo.GetExt() == "h") { hFilePath = fileName; fileNameInfo.SetExt("c"); if (fileNameInfo.Exists() && wxMessageBox(_("Also the file \"") + fileNameInfo.GetFullName() + _("\" will be generated. Do you want to overwrite it?"), _("Confirm"), wxYES_NO) == wxNO) { return; } cFilePath = fileNameInfo.GetFullPath(); } else if (fileNameInfo.GetExt() == "c") { cFilePath = fileName; fileNameInfo.SetExt("h"); if (fileNameInfo.Exists() && wxMessageBox(_("The file \"") + fileNameInfo.GetFullName() + _("\" will be generated. Do you want to overwrite it?"), _("Confirm"), wxYES_NO) == wxNO) { return; } hFilePath = fileNameInfo.GetFullPath(); } wxFFileOutputStream hFile(hFilePath); wxFFileOutputStream cFile(cFilePath); wxTextOutputStream hOut(hFile); wxTextOutputStream cOut(cFile); EMGL_font_t *font = LoadEMGLFont(charmap, compress, format); hOut << GetHeaderFile(fileNameInfo.GetName()); cOut << GetSourceFile(font, fileNameInfo.GetName()); DeleteEMGLFont(font); }
void savePng(GImage* pImage, const char* szFilename) { FILE* pFile = fopen(szFilename, "wb"); if(!pFile) throw Ex("Failed to create file: ", szFilename); FileHolder hFile(pFile); savePng(pImage, pFile); }
bool FileTransaction::SetModificationTime(const WCHAR *filePath, FILETIME lastMod) { if (!hTrans) return file::SetModificationTime(filePath, lastMod); ScopedHandle hFile(CreateFile(filePath, GENERIC_READ | GENERIC_WRITE, OPEN_EXISTING)); if (INVALID_HANDLE_VALUE == hFile) return false; return SetFileTime(hFile, NULL, NULL, &lastMod); }
LRESULT TextFrame::OnCreate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled) { ctrlPad.Create(m_hWnd, rcDefault, NULL, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_VSCROLL | ES_AUTOVSCROLL | ES_MULTILINE | ES_NOHIDESEL | ES_READONLY, WS_EX_CLIENTEDGE); ctrlPad.LimitText(0); ctrlPad.SetFont(Fonts::g_font); try { File hFile(file, File::READ, File::OPEN); string str = hFile.read(4); static BYTE bUTF8signature[] = {0xef, 0xbb, 0xbf}; static BYTE bUnicodeSignature[] = {0xff, 0xfe}; int nFormat = SF_TEXT; if (memcmp(str.c_str(), bUTF8signature, sizeof(bUTF8signature)) == 0) { nFormat = SF_TEXT | SF_USECODEPAGE | (CP_UTF8 << 16); hFile.setPos(_countof(bUTF8signature)); } else if (memcmp(str.c_str(), bUnicodeSignature, sizeof(bUnicodeSignature)) == 0) { nFormat = SF_TEXT | SF_UNICODE; hFile.setPos(_countof(bUnicodeSignature)); } else { nFormat = SF_TEXT; hFile.setPos(0); } EDITSTREAM es = { (DWORD_PTR)&hFile, 0, EditStreamCallback }; ctrlPad.StreamIn(nFormat, es); ctrlPad.EmptyUndoBuffer(); SetWindowText(Text::toT(Util::getFileName(Text::fromT(file))).c_str()); } catch (const FileException& e) { SetWindowText(Text::toT(Util::getFileName(Text::fromT(file)) + ": " + e.getError()).c_str()); } bHandled = FALSE; return 1; }
void DVLib::FileCreate( const std::wstring& filename, DWORD dwDesiredAccess, // GENERIC_READ | GENERIC_WRITE DWORD dwShareMode, // 0 DWORD dwCreationDisposition, // CREATE_ALWAYS DWORD dwFlagsAndAttributes) // FILE_ATTRIBUTE_NORMAL) { auto_hfile hFile(::CreateFile(filename.c_str(), dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, dwFlagsAndAttributes, NULL)); CHECK_WIN32_BOOL(get(hFile) != NULL, L"Error opening \"" << filename << L"\""); }
MapFile(void) : data(NULL), #ifdef HAVE_MMAP mmap_fd(-1) #elif defined(_WIN32) hFile(0), hFileMap(0) #endif { } ~MapFile(); bool open(const char *file_name, unsigned long file_size); inline gchar *begin(void) { return data; } private:
bool LogviewDialog::parseLogFile(std::vector<logFileFormat> &data, char *filePath) { /* Read the log data into a string */ std::string logData; std::ifstream hFile(filePath); if (hFile.is_open()) { while (hFile.good()) { std::string tmp; std::getline(hFile, tmp); logData.append(tmp); } hFile.close(); } else { return false; } /* Parse log file by lines (can't trust new line to work) */ std::vector<std::string> lines; char *ln = strtok((char*)logData.c_str(), "["); while (ln != NULL) { std::string tmp = "["; tmp += ln; lines.push_back(tmp); ln = strtok(NULL, "["); } /* Use tokenizer to separate elements and place into struct */ for (std::vector<std::string>::iterator it = lines.begin(); it != lines.end(); it++) { logFileFormat lff; char *pch = strtok((char*)it->c_str(), "[ ]"); if (pch != NULL) lff.date = pch; pch = strtok(NULL, " *"); if (pch != NULL) lff.urgency = pch; pch = strtok(NULL, "*["); if (pch != NULL) lff.info = pch; data.push_back(lff); } return true; }
bool FileTransaction::WriteAll(const WCHAR *filePath, const void *data, size_t dataLen) { if (!hTrans) return file::WriteAll(filePath, data, dataLen); ScopedHandle hFile(CreateFile(filePath, GENERIC_WRITE, CREATE_ALWAYS)); if (INVALID_HANDLE_VALUE == hFile) return false; DWORD size; BOOL ok = WriteFile(hFile, data, (DWORD)dataLen, &size, NULL); assert(!ok || (dataLen == (size_t)size)); return ok && dataLen == (size_t)size; }
bool CoImageTIF::Encode(FILE* pFile, bool bAppend) { if (EncodeSafeCheck(pFile)) return false; XFileDisk hFile(pFile); try { if (&hFile==NULL) throw CVLIB_IMG_ERR_NOFILE; // if (GetPalette() == NULL) throw CVLIB_IMG_ERR_NOIMAGE; // <RJ> replaced "w+b" with "a", to append an image directly on an existing file if (m_tif2==NULL) m_tif2 =(void*)_TIFFOpenEx(&hFile, "a"); if (m_tif2==NULL) throw "initialization fail"; if (bAppend || m_pages) m_multipage=true; m_pages++; if (!EncodeBody(m_tif2,m_multipage,m_pages,m_pages)) throw "Error saving TIFF file"; if (bAppend) { if (!TIFFWriteDirectory((TIFF*)m_tif2)) throw "Error saving TIFF directory"; } } catch (char *message) { strncpy(m_Info.szLastError,message,255); if (m_tif2) { TIFFClose((TIFF*)m_tif2); m_tif2=NULL; m_multipage=false; m_pages=0; } return false; } if (!bAppend) { TIFFClose((TIFF*)m_tif2); m_tif2=NULL; m_multipage=false; m_pages=0; } return true; }
void GetLastWriteTime(const char* path, FILETIME* pFileTime) { AutoCloseHandle hFile(CreateFileA( path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL )); if(hFile.handle == INVALID_HANDLE_VALUE) throw formatted_exception() << "Could not open file '" << path << "' to get last write time."; if(!GetFileTime(hFile.handle, NULL, NULL, pFileTime)) throw formatted_exception() << "Could not get last write time for '" << path << "'."; }
void classISQL::OpenSQL() { QMultiLineEdit *txt; if ( pTabBar->currentTab() == 0 ) { pSliderRecentSQL->setValue( pSliderRecentSQL->maxValue() ); txt = txtSQL; } else txt = txtResults; // LET USER PICK A FILE QString qsFile = QFileDialog::getOpenFileName(); if ( qsFile.isNull() ) return; // TRY TO LOAD THE FILE QFile hFile( qsFile ); if ( !hFile.open( IO_ReadOnly ) ) return; txt->setAutoUpdate( FALSE ); txt->clear(); QTextStream t( &hFile ); while ( !t.eof() ) { QString s = t.readLine(); txt->append( s ); } hFile.close(); txt->setAutoUpdate( TRUE ); txt->repaint(); if ( pTabBar->currentTab() == 0 ) qsSQLFileName = qsFile; else qsResultsFileName = qsFile; setTextType( 0 ); }
void crash_handler::create_log_file_for_hockey_app(EXCEPTION_POINTERS* /* pExcPtrs */) { const int max_stack_trace_depth = 48; void *stack[max_stack_trace_depth]; USHORT count = CaptureStackBackTrace(0, max_stack_trace_depth, stack, NULL); std::stringstream stack_trace_stream; for (USHORT c = 0; c < count; c++) { stack_trace_stream << stack[c] << ";"; } std::string stack_trace = stack_trace_stream.str(); std::wstring log_name = get_report_log_path(); time_t now = time(0); std::stringstream log_stream; // TODO (*) : use real info about app log_stream << "Package: " << product_bundle << std::endl; log_stream << "Version: " << VERSION_INFO_STR << std::endl; log_stream << "OS: " << get_os_version() << std::endl; log_stream << "Manufacturer: MS" << std::endl; log_stream << "Model: " << tools::version_info().get_version() << std::endl; char str[26]; ctime_s(str, sizeof str, &now); log_stream << "Date: " << str << std::endl; log_stream << stack_trace << std::endl; auto log_text = log_stream.str(); DWORD dwWritten; HANDLE handleFile (CreateFile(log_name.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0)); // https://msdn.microsoft.com/ru-ru/library/windows/desktop/5fc6ft2t(v=vs.80).aspx if(handleFile == INVALID_HANDLE_VALUE) { return; } CHandle hFile(handleFile); WriteFile(hFile, log_text.c_str(), log_text.size(), &dwWritten, 0); }
void classISQL::SaveAsSQL() { QMultiLineEdit *txt; QString qsFileName; if ( pTabBar->currentTab() == 0 ) { txt = txtSQL; qsFileName = qsSQLFileName; } else { txt = txtResults; qsFileName = qsResultsFileName; } // LET USER PICK A FILE QString qsFile = QFileDialog::getSaveFileName( qsFileName ); if ( qsFile.isNull() ) return; // TRY TO SAVE THE FILE QFile hFile( qsFile ); if ( !hFile.open( IO_WriteOnly ) ) return; hFile.writeBlock( txt->text(), txt->text().length() ); hFile.close(); if ( pTabBar->currentTab() == 0 ) { qsSQLFileName = qsFile; } else { qsResultsFileName = qsFile; } }
void MCF::saveMCF_Header() { //donot use getDLSize here as the file might have a gap in it. :( uint64 offset = 0; for (size_t x=0; x<m_pFileList.size(); x++) { MCFFile* file = m_pFileList[x]; if (!file->isSaved()) continue; uint64 pos = file->getOffSet() + file->getCurSize(); if (offset < pos) offset = pos; uint64 diffpos = file->getDiffOffSet() + file->getDiffSize(); if (file->hasDiff() && offset < diffpos) offset = diffpos; } if (offset == 0) offset = m_sHeader->getSize(); UTIL::FS::recMakeFolder(UTIL::FS::PathWithFile(m_szFile)); UTIL::FS::FileHandle hFile(m_szFile.c_str(), UTIL::FS::FILE_APPEND); hFile.seek(offset); XMLSaveAndCompress sac(&hFile, isCompressed()); genXml(&sac); sac.finish(); m_sHeader->setXmlStart(offset); m_sHeader->setXmlSize((uint32)sac.getTotalSize()); m_sHeader->saveToFile(hFile); }
void MCF::preAllocateFile() { uint64 offset = getDLSize() + m_sHeader->getSize(); UTIL::FS::recMakeFolder(UTIL::FS::PathWithFile(m_szFile)); UTIL::FS::FileHandle hFile(m_szFile.c_str(), UTIL::FS::FILE_APPEND); uint64 pos = UTIL::FS::getFileSize(m_szFile.c_str()); MCFCore::Misc::ProgressInfo prog; prog.totalAmmount = offset; //we do this as if its a massive file. Seeking will zero the end and take ages while (pos < offset) { if (m_bStopped) break; pos += 10*1024*1024; if (pos > offset) pos = offset; hFile.seek(pos); prog.percent = (uint8)(pos * 100 / offset); prog.doneAmmount = pos; onProgressEvent(prog); } if (!m_bStopped) return; // Got canceled hFile.close(); UTIL::FS::delFile(m_szFile.c_str()); }
void DVLib::FileWrite( const std::wstring& filename, const std::vector<char>& data, DWORD dwShareMode, // GENERIC_READ | GENERIC_WRITE DWORD dwCreationDisposition, // CREATE_ALWAYS DWORD dwFlagsAndAttributes) // FILE_ATTRIBUTE_NORMAL) { auto_hfile hFile(::CreateFile(filename.c_str(), dwShareMode, 0, NULL, dwCreationDisposition, dwFlagsAndAttributes, NULL)); CHECK_WIN32_BOOL(get(hFile) != NULL, L"Error opening " << filename); if (data.size() > 0) // empty files are ok { DWORD dwWritten = 0; CHECK_WIN32_BOOL(::WriteFile(get(hFile), & * data.begin(), data.size(), & dwWritten, NULL), L"Error writing " << data.size() << " byte(s) to \"" << filename << L"\""); CHECK_BOOL(dwWritten == data.size(), L"Invalid number of bytes written."); } }
std::vector<char> DVLib::FileReadToEnd(const std::wstring& filename) { std::vector<char> data; long size = GetFileSize(filename); if (size > 0) { auto_hfile hFile(::CreateFile(filename.c_str(), GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)); CHECK_WIN32_BOOL(get(hFile) != NULL, L"Error opening \"" << filename << L"\""); data.resize(size); DWORD dwRead = 0; CHECK_WIN32_BOOL(::ReadFile(get(hFile), & * data.begin(), size, & dwRead, NULL), L"Error reading \"" << filename << L"\""); CHECK_BOOL(static_cast<long>(dwRead) == size, L"Invalid number of bytes read from \"" << filename << L"\""); } return data; }
void Settings::init() { QString hPath = "./config.ini"; QString sPath = "../confs.ini"; QFile hFile(hPath); if (hFile.open(QIODevice::ReadWrite)) hFile.close(); else { QMessageBox::critical( NULL, QObject::tr("File cannot be created"), QObject::tr("Horus config file cannot be created."), QObject::tr("Ok"), 0); exit(EXIT_FAILURE); } QFile sFile(sPath); if (sFile.open(QIODevice::ReadOnly)) sFile.close(); else { QMessageBox::critical( NULL, QObject::tr("File cannot be opened"), QObject::tr("Server config file cannot be opened."), QObject::tr("Ok"), 0); exit(EXIT_FAILURE); } settingsHorus = new QSettings(hPath, QSettings::IniFormat); settingsServer = new QSettings(sPath, QSettings::IniFormat); settingsHorus->setIniCodec("utf8"); settingsServer->setIniCodec("utf8"); }
bool Engine::isRunnable() { Application& app = Application::instance(); int hashes = 0; string hFile(getHashFile()); string line; if (DEBUG) app.logger().information(format("%%Loading hash file %s...", hFile)); // make sure the hash file exists Poco::File f(hFile); if (!f.exists()) { app.logger().information("|Unable to find hash file"); return false; } // open the has file FileInputStream fis(hFile); if (!fis.good()) { app.logger().information("|Unable to load hash file"); return false; } // count entries while(fis >> line) { if(!line.empty()) hashes++; } if(hashes>0) return true; if(DEBUG) { app.logger().information("%No hashes to load"); } return false; }
FileLoader::ImageData FileLoader::loadBmp(const char* FilePath) { std::fstream hFile(FilePath, std::ios::in | std::ios::binary); if (!hFile.is_open()) throw std::invalid_argument("Error: File Not Found."); hFile.seekg(0, std::ios::end); int length = hFile.tellg(); hFile.seekg(0, std::ios::beg); std::vector<std::uint8_t> FileInfo(length); hFile.read(reinterpret_cast<char*>(FileInfo.data()), 54); if(FileInfo[0] != 'B' && FileInfo[1] != 'M') { hFile.close(); throw std::invalid_argument("Error: Invalid File Format. Bitmap Required."); } if (FileInfo[28] != 24 && FileInfo[28] != 32) { hFile.close(); throw std::invalid_argument("Error: Invalid File Format. 24 or 32 bit Image Required."); } short BitsPerPixel = FileInfo[28]; int width = FileInfo[18] + (FileInfo[19] << 8); int height = FileInfo[22] + (FileInfo[23] << 8); std::uint32_t PixelsOffset = FileInfo[10] + (FileInfo[11] << 8); std::uint32_t size = ((width * BitsPerPixel + 31) / 32) * 4 * height; mImageData.pixels.resize(size); hFile.seekg (PixelsOffset, std::ios::beg); hFile.read(reinterpret_cast<char*>(mImageData.pixels.data()), size); hFile.close(); // // Data read from the header of the BMP file // unsigned char header[54]; // unsigned int dataPos; // unsigned int imageSize; // unsigned int width, height; // // Actual RGB data //// unsigned char * data; // // // Open the file // FILE * file = fopen(FilePath,"rb"); // if (!file) // { // printf("File could not be opened. Are you in the right directory ? Don't forget to read the FAQ !\n"); // return FileLoader::ImageData(); // } // // // Read the header, i.e. the 54 first bytes // // // If less than 54 bytes are read, problem // if ( fread(header, 1, 54, file)!=54 ){ // printf("Not a correct BMP file\n"); // return FileLoader::ImageData(); // } // // A BMP files always begins with "BM" // if ( header[0]!='B' || header[1]!='M' ){ // printf("Not a correct BMP file\n"); // return FileLoader::ImageData(); // } // // Make sure this is a 24bpp file // if ( *(int*)&(header[0x1E])!=0 ) // { // printf("Not a correct BMP file\n"); // return FileLoader::ImageData(); // } // if ( *(int*)&(header[0x1C])!=24 ) // { // printf("Not a correct BMP file\n"); // return FileLoader::ImageData(); // } // // // Read the information about the image // dataPos = *(int*)&(header[0x0A]); // imageSize = *(int*)&(header[0x22]); // width = *(int*)&(header[0x12]); // height = *(int*)&(header[0x16]); // // // Some BMP files are misformatted, guess missing information // if (imageSize==0) imageSize=width*height*3; // 3 : one byte for each Red, Green and Blue component // if (dataPos==0) dataPos=54; // The BMP header is done that way // // // Create a buffer // //data = new unsigned char [imageSize]; // mImageData.pixels.resize(imageSize); // // Read the actual data from the file into the buffer // fread(&mImageData.pixels[0],1,imageSize,file); // // // Everything is in memory now, the file wan be closed // fclose (file); // mImageData.width = width; mImageData.height = height; mImageData.hasAlpha = BitsPerPixel == 32 ? true : false; return mImageData; }
void TestRunner::compile() { // Check when is the last time that the test source has been modified const QString filePath = inDir_.filePath(fileName_); const QFileInfo fileInfo(filePath); const QDateTime lastModified = fileInfo.lastModified(); // Compile if necessary Status s = status(); bool notCompiledYet = (s == Status::NotCompiledYet) || (s == Status::CompileError); bool modified = (lastCompiled_ < lastModified); bool processing = (s == Status::Compiling) || (s == Status::Running); if (notCompiledYet || (modified && !processing)) { setStatus_(Status::Compiling); compileOutput_.clear(); lastCompiled_ = lastModified; // -------- Go to folder where to compile test -------- QString compileDirPath = outDir_.absoluteFilePath(testName_); compileDir_ = outDir_; if (!compileDir_.cd(testName_)) { // Create folder since it doesn't exist if (!outDir_.mkdir(testName_)) { failCompilation_("Can't create build folder " + compileDirPath); return; } // Go to folder where to compile test // This is hard to reach (if we manage to create the folder, surely // we can cd to it), but doesn't hurt to check. if (!compileDir_.cd(testName_)) { failCompilation_("Can't create build folder " + compileDirPath); return; } } // -------- Open all files for reading or writing -------- const QString hFileName = testName_ + ".gen.h"; const QString cppFileName = testName_ + ".gen.cpp"; const QString proFileName = testName_ + ".gen.pro"; const QString hFilePath = compileDir_.filePath(hFileName); const QString cppFilePath = compileDir_.filePath(cppFileName); const QString proFilePath = compileDir_.filePath(proFileName); QFile sourceFile(filePath); QFile hFile(hFilePath); QFile cppFile(cppFilePath); QFile proFile(proFilePath); if (!sourceFile.open(QFile::ReadOnly | QFile::Text)) { failCompilation_("Can't open " + filePath); return; } if (!hFile.open(QFile::WriteOnly | QFile::Text)) { failCompilation_("Can't write " + hFilePath); return; } if (!cppFile.open(QFile::WriteOnly | QFile::Text)) { failCompilation_("Can't write " + cppFilePath); return; } if (!proFile.open(QFile::WriteOnly | QFile::Text)) { failCompilation_("Can't write " + proFilePath); return; } // -------- Read source file -------- QTextStream sourceStream(&sourceFile); const QString testSource = sourceStream.readAll(); // -------- Generate and write test gen files -------- QTextStream hStream(&hFile); QTextStream cppStream(&cppFile); QTextStream proStream(&proFile); hStream << generateH(testName_, testSource); cppStream << generateCpp(testName_, testSource); proStream << generatePro(testName_, testSource); // -------- Run qmake -------- QString program = QMAKE_QMAKE_QMAKE; QStringList arguments; arguments << "-spec" << QMAKE_QMAKESPEC << proFilePath; compileOutput_ += getCurrentTime() + ": Starting: \"" + program + "\" " + arguments.join(' ') + "\n"; process_->setWorkingDirectory(compileDirPath); connect(process_, static_cast<void (QProcess::*)(int, QProcess::ExitStatus)>(&QProcess::finished), this, &TestRunner::compile_onQmakeFinished_); emit outputChanged(); process_->start(program, arguments); // -> go read qMakeFinished_(int exitCode) now. } else { emit compileFinished(true); } }
int main(int argc, char* argv[]) { int run_num = 0; run_num = atoi(argv[1]); //read in the run number of this simulation int seed = 0; seed = atoi(argv[2]); //read in the seed for the random number generator of this simulation srand(seed); int arg = 0; int typeTest = 0; typeTest = atoi(argv[3]); //read the type of test this simulation is doing int tempTTTindex = 0; int temphysindex = 0; std::string folder = ""; //case statement of the different simulation type with TTT and hys values //as well as the folder to output to switch(typeTest) { case 0: folder = "high"; tempTTTindex = 15; temphysindex = 20; arg = 3; break; case 1: folder = "highhys"; tempTTTindex = 3; temphysindex = 15; arg = 3; break; case 2: folder = "low"; tempTTTindex = 0; temphysindex = 0; arg = 3; break; case 3: folder = "mid"; tempTTTindex = 7; temphysindex = 10; arg = 3; break; case 4: folder = "opthigh"; tempTTTindex = 15; temphysindex = 20; arg = 2; break; case 5: folder = "opthighhys"; tempTTTindex = 3; temphysindex = 15; arg = 2; break; case 6: folder = "optlow"; tempTTTindex = 0; temphysindex = 0; arg = 2; break; case 7: folder = "optmid"; tempTTTindex = 7; temphysindex = 10; arg = 2; break; default: // program should not reach here break; } //set the TTTindex array to the correct values for(int j=0; j<NUM_BASESTATION; j++) { TTTindex[j] = tempTTTindex; } //set the hysindex array to the correct values for(int k=0; k<NUM_BASESTATION; k++) { hysindex[k] = temphysindex; } TTTmaxindex = 15; hysmaxindex = 20; TTTArray[0] = 0.0; TTTArray[1] = 0.04; TTTArray[2] = 0.064; TTTArray[3] = 0.08; TTTArray[4] = 0.1; TTTArray[5] = 0.128; TTTArray[6] = 0.16; TTTArray[7] = 0.256; TTTArray[8] = 0.32; TTTArray[9] = 0.48; TTTArray[10] = 0.512; TTTArray[11] = 0.64; TTTArray[12] = 1.024; TTTArray[13] = 1.280; TTTArray[14] = 2.56; TTTArray[15] = 5.12; hysArray[0] = 0.0; hysArray[1] = 0.5; hysArray[2] = 1.0; hysArray[3] = 1.5; hysArray[4] = 2.0; hysArray[5] = 2.5; hysArray[6] = 3.0; hysArray[7] = 3.5; hysArray[8] = 4.0; hysArray[9] = 4.5; hysArray[10] = 5.0; hysArray[11] = 5.5; hysArray[12] = 6.0; hysArray[13] = 6.5; hysArray[14] = 7.0; hysArray[15] = 7.5; hysArray[16] = 8.0; hysArray[17] = 8.5; hysArray[18] = 9.0; hysArray[19] = 9.5; hysArray[20] = 10.0; //set the TTT and hys arrays to the correct values for(int i=0; i<NUM_BASESTATION; i++) { TTT[i] = TTTArray[TTTindex[i]]; hys[i] = hysArray[hysindex[i]]; } // std::cout << "Enter what operation you would like to undertake.\n"; // std::cout << "1 for generating / updating policy\n"; // std::cout << "2 for using the policy\n"; // std::cout << "3 for no learning\n"; // std:: cout << "Please enter:\n"; // // int arg; // std::cin >> arg; //this block set the function variable. //if all the code is commented in and the code above commented out then //the simulation can be run with user given parameters instead of parameters //given by the bash script. if(arg == 1) { // q-learning printf("Q-Learning started...\n"); function = 1; } else if(arg == 2) { // use policy printf("Simulation started...\n"); // printf("Enter index for TTT\n"); // int tempTTTindex; // // std::cin >> tempTTTindex; // tempTTTindex = atoi(argv[4]); // for(int j=0; j<NUM_BASESTATION; j++) { // TTT[j] = TTTArray[tempTTTindex]; // TTTindex[j] = tempTTTindex; // } // // printf("Enter index for hys\n"); // int temphysindex; // // std::cin >> temphysindex; // temphysindex = atoi(argv[5]); // for(int k=0; k<NUM_BASESTATION; k++) { // hys[k] = hysArray[temphysindex]; // hysindex[k] = temphysindex; // } function = 2; } else if(arg == 3) { printf("No learning simulation...\n"); // printf("Enter index for TTT\n"); // int tempTTTindex; // // std::cin >> tempTTTindex; // tempTTTindex = atoi(argv[4]); // for(int j=0; j<NUM_BASESTATION; j++) { // TTT[j] = TTTArray[tempTTTindex]; // TTTindex[j] = tempTTTindex; // } // // printf("Enter index for hys\n"); // int temphysindex; // // std::cin >> temphysindex; // temphysindex = atoi(argv[5]); // for(int k=0; k<NUM_BASESTATION; k++) { // hys[k] = hysArray[temphysindex]; // hysindex[k] = temphysindex; // } function = 4; } //instantiate the q-learning agents for the base stations q[0] = new q_learning(gs,0,TTTindex[0],hysindex[0]); q[1] = new q_learning(gs,1,TTTindex[1],hysindex[1]); q[2] = new q_learning(gs,2,TTTindex[2],hysindex[2]); q[3] = new q_learning(gs,3,TTTindex[3],hysindex[3]); q[4] = new q_learning(gs,4,TTTindex[4],hysindex[4]); q[5] = new q_learning(gs,5,TTTindex[5],hysindex[5]); q[6] = new q_learning(gs,6,TTTindex[6],hysindex[6]); q[7] = new q_learning(gs,7,TTTindex[7],hysindex[7]); q[8] = new q_learning(gs,8,TTTindex[8],hysindex[8]); gs->start(); //start the scheduler //this is where the simulation returns to when the schedulers is stopped by a mobile //print the results for the base stations on screen and save the q-vaules and policy //for the q-learning agents to external files for (int l=0; l<NUM_BASESTATION; l++) { bStations[l]->print(); q[l]->saveQValues(); } //This block of code writes the results out to text files in folders for(int m=0; m<NUM_BASESTATION; m++) { std::stringstream hString; hString << "results/longer/" << folder << run_num << "/basestation" << m << "/handover.txt"; handoverString = hString.str(); std::stringstream dString; dString<< "results/longer/" << folder << run_num << "/basestation" << m << "/drop.txt"; dropString = dString.str(); std::stringstream pString; pString << "results/longer/" << folder << run_num << "/basestation" << m << "/ping.txt"; pingString = pString.str(); std::stringstream fString; fString << "results/longer/" << folder << run_num << "/basestation" << m << "/failure.txt"; failureString = fString.str(); std::stringstream sString; sString << "results/longer/" << folder << run_num << "/basestation" << m << "/state.txt"; stateString = sString.str(); std::ofstream hFile (handoverString); if(hFile.is_open()) { for (std::vector<double>::iterator it=handover_total[m].begin() ; it!=handover_total[m].end(); it++) { hFile << *it << "\n"; } } hFile.close(); std::ofstream dFile (dropString); if(dFile.is_open()) { for (std::vector<double>::iterator it=drop_total[m].begin() ; it!=drop_total[m].end(); it++) { dFile << *it << "\n"; } } dFile.close(); std::ofstream pFile (pingString); if(pFile.is_open()) { for (std::vector<double>::iterator it=pingpong_total[m].begin() ; it!=pingpong_total[m].end(); it++) { pFile << *it << "\n"; } } pFile.close(); std::ofstream fFile (failureString); if(fFile.is_open()) { for (std::vector<double>::iterator it=failure_total[m].begin() ; it!=failure_total[m].end(); it++) { fFile << *it << "\n"; } } fFile.close(); std::ofstream sFile (stateString); if(sFile.is_open()) { for (std::vector<int>::iterator it=stateChanges[m].begin() ; it!=stateChanges[m].end(); it++) { sFile << *it << "\n"; } } sFile.close(); } printf("end...\n"); delete gs; //delete the scheduler to clean up return 0; }
/******************************************************************************* * * 函 数 名 : GetPEFileBit * 功能描述 : 取得可执行文件的位数 * 参数列表 : pPEFilePath -- pe文件路径 * 说 明 : 读pe文件的头进内存,再调用GetBitByPEHeader去判断 * 返回结果 : 返回当前进程位数 * *******************************************************************************/ ULONG GetPEFileBit(__in_z CONST PTCHAR pPEFilePath) { ULONG uResult(0) ; HANDLE hFile(INVALID_HANDLE_VALUE) ; HANDLE hFileMap(NULL) ; LPVOID pAddr(NULL) ; __try { if (NULL == pPEFilePath) { OutputDebugString(TEXT("GetPEFileBit pPEFilePath can't NULL!\r\n")) ; __leave ; } if(FALSE == PathFileExists(pPEFilePath)) { OutputDebugString(TEXT("The file does not exist!\r\n")) ; __leave ; } hFile = CreateFile(pPEFilePath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL) ; if (INVALID_HANDLE_VALUE == hFile) { OutputErrorInformation(TEXT("GetPEFileBit"), TEXT("CreateFile")) ; __leave ; } hFileMap = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL) ; if (NULL == hFile) { OutputErrorInformation(TEXT("GetPEFileBit"), TEXT("CreateFileMapping")) ; __leave ; } pAddr = MapViewOfFile(hFileMap, FILE_MAP_READ, 0, 0, 0) ; if (NULL == pAddr) { OutputErrorInformation(TEXT("GetPEFileBit"), TEXT("MapViewOfFile")) ; __leave ; } uResult = GetBitByPEHeader(pAddr, GetFileSize(hFile, NULL)) ; } __finally { if (NULL != pAddr) { UnmapViewOfFile(pAddr) ; pAddr = NULL ; } if (NULL != hFileMap) { CloseHandle(hFileMap) ; hFileMap = NULL ; } if (INVALID_HANDLE_VALUE != hFile) { CloseHandle(hFile) ; hFile = INVALID_HANDLE_VALUE ; } } return uResult ; }
int _tmain(int argc, TCHAR* argv[]) { CoInitializeEx(NULL, COINIT_MULTITHREADED); try { if (argv[1] != 0 && argv[2] != 0 && argv[3] == 0) { CComPtr<IXMLDOMDocument2> xdoc; if (xdoc.CoCreateInstance(L"Msxml2.DOMDocument.6.0") != S_OK) throw MyMsgException(TEXT("Fail to create XML parser object!")); CComVariant strFileName; strFileName = SysAllocString( CT2CW(argv[1]) ); VARIANT_BOOL bIsSucc; xdoc->load(strFileName, &bIsSucc); if (bIsSucc != VARIANT_TRUE) throw MyMsgException(TEXT("Fail to load input file %s!"), argv[1]); CComPtr<IXMLDOMNode> xDllNameNode; CComBSTR strXPath; strXPath = L"/ImportLibrary/DllName"; xdoc->selectSingleNode(strXPath, &xDllNameNode); if (xDllNameNode == NULL) throw MyMsgException(TEXT("No DllName node!")); Sora::IImportLibraryBuilder* impBuilder; CComBSTR strDllName; xDllNameNode->get_text(&strDllName); CW2AEX<> cvtstrDllName(strDllName, CP_ACP); CComPtr<IXMLDOMNode> xAmd64Node; strXPath = L"/ImportLibrary/ArchAMD64"; xdoc->selectSingleNode(strXPath, &xAmd64Node); if (xAmd64Node == NULL) impBuilder = Sora::CreateX86ImpLibBuilder(cvtstrDllName, cvtstrDllName); else impBuilder = Sora::CreateX64ImpLibBuilder(cvtstrDllName, cvtstrDllName); strXPath = L"/ImportLibrary/Import"; CComPtr<IXMLDOMNodeList> xImportNodes; if (xdoc->selectNodes(strXPath, &xImportNodes) != S_OK) throw MyMsgException(TEXT("No Import nodes found!")); for(;;) { CComPtr<IXMLDOMNode> xImportNode; if (xImportNodes->nextNode(&xImportNode) != S_OK) break; CComPtr<IXMLDOMNode> xLinkNameNode, xStubNameNode, xImportNameNode, xImportOrdinalNode; CComBSTR strLinkName, strStubName, strImportName, strImportOrdinal; strXPath = L"./LinkName"; if (xImportNode->selectSingleNode(strXPath, &xLinkNameNode) != S_OK) throw MyMsgException(TEXT("No LinkName Node!")); strXPath = L"./StubName"; xImportNode->selectSingleNode(strXPath, &xStubNameNode); //if no stubname node found, will not generate callstub xLinkNameNode->get_text(&strLinkName); if (xStubNameNode != NULL) xStubNameNode->get_text(&strStubName); HRESULT selectImportName; HRESULT selectOrdinal; strXPath = L"./ImportName"; selectImportName = xImportNode->selectSingleNode(strXPath, &xImportNameNode); strXPath = L"./Ordinal"; selectOrdinal = xImportNode->selectSingleNode(strXPath, &xImportOrdinalNode); int nOrdinal = 0; if (selectImportName == S_OK || selectOrdinal == S_OK) { if (selectImportName == S_OK) xImportNameNode->get_text(&strImportName); if (selectOrdinal == S_OK) { xImportOrdinalNode->get_text(&strImportOrdinal); LPCWSTR pszImportOrdinal = strImportOrdinal; while(*pszImportOrdinal != 0) { nOrdinal *= 10; nOrdinal += *pszImportOrdinal - L'0'; ++pszImportOrdinal; } } if (selectImportName == S_OK && selectOrdinal == S_OK) { impBuilder->AddImportFunctionByNameWithHint( CW2AEX<>(strLinkName, CP_UTF8), CW2AEX<>(strStubName, CP_UTF8), CW2AEX<>(strImportName, CP_UTF8), nOrdinal ); } else if (selectImportName == S_OK) { impBuilder->AddImportFunctionByName( CW2AEX<>(strLinkName, CP_UTF8), CW2AEX<>(strStubName, CP_UTF8), CW2AEX<>(strImportName, CP_UTF8) ); } else if (selectOrdinal == S_OK) { impBuilder->AddImportFunctionByOrdinal( CW2AEX<>(strLinkName, CP_UTF8), CW2AEX<>(strStubName, CP_UTF8), nOrdinal ); } } else { throw MyMsgException(TEXT("No ImportName or Ordinal Node!")); } } //save file impBuilder->Build(); int nFileSize = impBuilder->GetDataLength(); CHandle hFile( CreateFile(argv[2], GENERIC_READ | GENERIC_WRITE, 0, 0, CREATE_ALWAYS, 0, NULL) ); if ( (HANDLE)hFile == INVALID_HANDLE_VALUE ) throw MyMsgException(TEXT("Fail to create library File %s!"), argv[2]); if (SetFilePointer(hFile, nFileSize, 0, FILE_BEGIN) == INVALID_SET_FILE_POINTER) if (GetLastError() != 0) throw MyMsgException(TEXT("Can't allocate disk space for output file!")); if (SetEndOfFile(hFile) == FALSE) throw MyMsgException(TEXT("Can't allocate disk space for output file!")); CHandle hFileMap( CreateFileMapping(hFile, 0, PAGE_READWRITE, 0, nFileSize, 0) ); if ((HANDLE)hFileMap == NULL) throw MyMsgException(TEXT("Can't map output file for writing!")); LPVOID pFile = MapViewOfFile(hFileMap, FILE_MAP_WRITE, 0, 0, 0); if (pFile == 0) throw MyMsgException(TEXT("Can't map output file for writing!")); impBuilder->GetRawData((PBYTE)pFile); impBuilder->Dispose(); UnmapViewOfFile(pFile); } else { fprintf(stdout, "%s", "Make import library from XML\n" "using: MakeImpLib <input xml> <output lib>\n" "\n" "XML Sample\n" "<ImportLibrary>\n" " <!-- <ArchAMD64 /> -->\n" " <!-- If no ArchAMD64 node, it creates i386 import library -->\n" " <DllName>Kernel32.dll</DllName>\n" " <Import>\n" " <LinkName>__imp__SleepEx@8</LinkName>\n" " <!-- StubName can be removed, so no call stub will generated -->\n" " <StubName>_SleepEx@8</StubName>\n" " <!-- For Ordinal and ImportName, you can use either or both -->\n" " <!-- When use both, it's import by name and ordinal works as hint -->\n" " <!-- In most case only ImportName is used, that's enough -->\n" " <!-- But you can't strip both -->\n" " <Ordinal>1208</Ordinal>\n" " <ImportName>SleepEx</ImportName>\n" " </Import>\n" " <Import>\n" " <LinkName>__imp__WaitForSingleObject@8</LinkName>\n" " <ImportName>WaitForSingleObject</ImportName>\n" " </Import>\n" "</ImportLibrary>\n" "\n" "<?xml version=\"1.0\" encoding=\"UTF-8\"?> is needed " "for filename or function other than English letters.\n" ); } } catch (MyMsgException e) { fprintf(stderr, CT2CA(e.fmt), CT2CA(e.msg)); } CoUninitialize(); }
// This method creates minidump of the process void crash_handler::create_mini_dump(EXCEPTION_POINTERS* pExcPtrs) { MINIDUMP_EXCEPTION_INFORMATION mei; MINIDUMP_CALLBACK_INFORMATION mci; // Load dbghelp.dll HMODULE hDbgHelp = LoadLibrary(_T("dbghelp.dll")); if(hDbgHelp == NULL) { // Error - couldn't load dbghelp.dll return; } // create folder if not existed if (!CreateDirectory((get_report_path() + std::wstring(L"\\")).c_str(), NULL) && ERROR_ALREADY_EXISTS != GetLastError()) { return; } create_log_file_for_hockey_app(pExcPtrs); // Create the minidump file HANDLE handleFile (CreateFile( get_report_mini_dump_path().c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL)); // https://msdn.microsoft.com/ru-ru/library/windows/desktop/5fc6ft2t(v=vs.80).aspx if(handleFile==INVALID_HANDLE_VALUE) { return; } CHandle hFile(handleFile); // Write minidump to the file mei.ThreadId = GetCurrentThreadId(); mei.ExceptionPointers = pExcPtrs; mei.ClientPointers = FALSE; mci.CallbackRoutine = NULL; mci.CallbackParam = NULL; typedef BOOL (WINAPI *LPMINIDUMPWRITEDUMP)( HANDLE hProcess, DWORD ProcessId, HANDLE hFile, MINIDUMP_TYPE DumpType, CONST PMINIDUMP_EXCEPTION_INFORMATION ExceptionParam, CONST PMINIDUMP_USER_STREAM_INFORMATION UserEncoderParam, CONST PMINIDUMP_CALLBACK_INFORMATION CallbackParam); LPMINIDUMPWRITEDUMP pfnMiniDumpWriteDump = (LPMINIDUMPWRITEDUMP)GetProcAddress(hDbgHelp, "MiniDumpWriteDump"); if(!pfnMiniDumpWriteDump) { // Bad MiniDumpWriteDump function return; } HANDLE hProcess = GetCurrentProcess(); DWORD dwProcessId = GetCurrentProcessId(); auto dump_type = (_MINIDUMP_TYPE)get_dump_type(); if (dump_type == -1) { assert(!"dump_type must be positive"); dump_type = MiniDumpNormal; } BOOL bWriteDump = pfnMiniDumpWriteDump( hProcess, dwProcessId, hFile, dump_type, &mei, NULL, &mci); if(!bWriteDump) { // Error writing dump. return; } // Unload dbghelp.dll FreeLibrary(hDbgHelp); }
void DataCreator::CreateDB(const std::string & configFile, bool makeHuman) { std::ifstream dataFormat(configFile.c_str()); std::string tabName; while(!std::getline(dataFormat,tabName).eof()) { std::string tableName = "Data/" + tabName; std::ofstream oFile (tableName.c_str(), std::ios::out | std::ios::binary); std::string numFields; std::string numRecords; std::string numBytes; std::getline(dataFormat,numFields,'|'); std::getline(dataFormat,numRecords,'|'); std::getline(dataFormat,numBytes); int nFields = atoi(numFields.c_str()); int nRecords = atoi(numRecords.c_str()); int nBytes = atoi(numBytes.c_str()); std::vector<std::pair<bool,int> > * types = new std::vector<std::pair<bool, int> >(); char * record_buf = new char[nBytes*nRecords]; std::cout << "creating " << tabName << "...generating synthetic data..."; std::cout.flush(); for(int i = 0; i < nFields; i++) { std::string fType; std::getline(dataFormat,fType,'|'); if(fType.compare("int") == 0) { std::pair<bool,int> ty(true,4); //ty = std::make_pair(true,4); types->push_back(ty); std::string iType; std::getline(dataFormat,iType,'|'); if(iType.compare("incr") == 0) { std::string start; std::getline(dataFormat,start); int s = atoi(start.c_str()); for (int k = 0; k < nRecords; k++) { int field = k; memcpy(record_buf + (nBytes*k)+s,&field,sizeof(field)); } } else if(iType.compare("randIncr") == 0) { std::string start; std::getline(dataFormat,start); int s = atoi(start.c_str()); int field = rand() % 50; memcpy(record_buf +s,&field,sizeof(field)); for (int k = 1; k < nRecords; k++) { int inc = (rand() % 100) + 1; field += inc; memcpy(record_buf+(nBytes*k)+s,&field,sizeof(field)); } } else if(iType.compare("range") == 0) { std::string lower; std::string upper; std::string nLower; std::string nUpper; std::getline(dataFormat,lower,'|'); std::getline(dataFormat,upper,'|'); std::getline(dataFormat,nLower,'|'); std::getline(dataFormat,nUpper,'|'); std::string start; std::getline(dataFormat,start); int s = atoi(start.c_str()); int lB = atoi(lower.c_str()); int uB = atoi(upper.c_str()); int nLB = atoi(nLower.c_str()); int nUB = atoi(nUpper.c_str()); int diff = uB - lB + 1; for (int k = 0; k < nRecords; k++) { int field = rand() % diff + lB; if ((field < nUB) && (field > nLB)) { field = rand() % (1+lB-nLB) + lB; } memcpy(record_buf + (nBytes*k)+s, &field, sizeof(field)); } } else if(iType.compare("oddRange") == 0) { std::string lower; std::string upper; std::getline(dataFormat,lower,'|'); std::getline(dataFormat,upper,'|'); std::string start; std::getline(dataFormat,start); int s = atoi(start.c_str()); int lB = atoi(lower.c_str()); int uB = atoi(upper.c_str()); int diff = uB - lB + 1; for (int k = 0; k < nRecords; k++) { int field = (rand() % diff) + lB; if ((field % 2) == 0) { if (field == uB) { field--; } else { field++; } } memcpy(record_buf + (nBytes*k)+s, &field, sizeof(field)); } } else if(iType.compare("evenRange") == 0) { std::string lower; std::string upper; std::getline(dataFormat,lower,'|'); std::getline(dataFormat,upper,'|'); std::string start; std::getline(dataFormat,start); int s = atoi(start.c_str()); int lB = atoi(lower.c_str()); int uB = atoi(upper.c_str()); int diff = uB - lB + 1; for (int k = 0; k < nRecords; k++) { int field = (rand() % diff) + lB; if ((field % 2) != 0) { if (field == uB) { field--; } else { field++; } } memcpy(record_buf + (nBytes*k)+s, &field, sizeof(field)); } } else { std::string start; std::getline(dataFormat,start); int s = atoi(start.c_str()); for (int k = 0; k <nRecords; k++) { int field = rand(); memcpy(record_buf + (nBytes*k)+s, &field, sizeof(field)); } } } else if (fType.compare("fk") == 0) { std::pair<bool,int> ty(true,4); //ty = std::make_pair(true,4); types->push_back(ty); std::string lower; std::string upper; std::string nLower; std::string nUpper; std::getline(dataFormat,lower,'|'); std::getline(dataFormat,upper,'|'); std::getline(dataFormat,nLower,'|'); std::getline(dataFormat,nUpper,'|'); std::string start; std::getline(dataFormat,start); int s = atoi(start.c_str()); int lB = atoi(lower.c_str()); int uB = atoi(upper.c_str()); int nLB = atoi(nLower.c_str()); int nUB = atoi(nUpper.c_str()); int diff = uB - lB + 1; std::vector<int> * fKey = new std::vector<int>(); for (int k = 0; k < nRecords; k++) { int field = rand() % diff + lB; if ((field < nUB) && (field > nLB)) { field = rand() % (1+lB-nLB) + lB; } fKey->push_back(field); } std::vector<int>::iterator it; sort (fKey->begin(), fKey->end()); std::cerr << fKey->size() << "\n"; for (int l = 0; l < nRecords; l++) { int a = fKey->at(l); memcpy(record_buf + (nBytes*l)+s, &a, sizeof(a)); } } else { std::string numChar; std::getline(dataFormat,numChar,'|'); int nChar = atoi(numChar.c_str()); char * field = new char[nChar+1]; std::string start; std::getline(dataFormat,start); int s = atoi(start.c_str()); for (int k = 0; k < nRecords; k++) { for (int z = 0; z < nChar; z++) { int n = rand() % 26; char c = (char)(n+65); field[z] = c; } memcpy(record_buf + (nBytes*k)+s, field, nChar); field[nChar] = 0; std::pair<bool,int> ty(false,nChar); //ty = std::make_pair(false,nChar); types->push_back(ty); } } } std::cout << "saving..."; std::cout.flush(); oFile.write(record_buf, nBytes*nRecords); oFile.close(); std::cout << "done!" << std::endl; if(makeHuman) { int offset = 0; std::string hName = tableName + ".out"; std::ofstream hFile(hName.c_str()); for (int b = 0; b < nRecords; b++) { for (int a = 0; a < nFields; a++) { std::pair<bool,int> ty = types->at(a); if (ty.first) { int number; memcpy(&number, record_buf + offset, sizeof(int)); hFile << number << "|"; offset += 4; } else { int nChar = ty.second; char * str = new char[nChar+1]; memset(str,0,nChar+1); memcpy(str, record_buf+offset, nChar); offset += nChar; hFile << str << "|"; } } hFile << "\n"; } hFile.close(); } delete record_buf; } dataFormat.close(); }
//***************************************************************************** // Open the base file on top of: (a) file, (b) memory buffer, or (c) stream. // If create flag is specified, then this will create a new file with the // name supplied. No data is read from an opened file. You must call // MapFileToMem before doing direct pointer access to the contents. //***************************************************************************** HRESULT StgIO::Open( // Return code. LPCWSTR szName, // Name of the storage. int fFlags, // How to open the file. const void *pbBuff, // Optional buffer for memory. ULONG cbBuff, // Size of buffer. IStream *pIStream, // Stream for input. LPSECURITY_ATTRIBUTES pAttributes) // Security token. { HRESULT hr; // If we were given the storage memory to begin with, then use it. if (pbBuff && cbBuff) { _ASSERTE((fFlags & DBPROP_TMODEF_WRITE) == 0); // Save the memory address and size only. No handles. m_pData = (void *) pbBuff; m_cbData = cbBuff; // All access to data will be by memory provided. if ((fFlags & DBPROP_TMODEF_SHAREDMEM) == DBPROP_TMODEF_SHAREDMEM) { // We're taking ownership of this memory m_pBaseData = m_pData; m_iType = STGIO_SHAREDMEM; } else { m_iType = STGIO_MEM; } goto ErrExit; } // Check for data backed by a stream pointer. else if (pIStream) { // If this is for the non-create case, get the size of existing data. if ((fFlags & DBPROP_TMODEF_CREATE) == 0) { LARGE_INTEGER iMove = { { 0, 0 } }; ULARGE_INTEGER iSize; // Need the size of the data so we can map it into memory. if (FAILED(hr = pIStream->Seek(iMove, STREAM_SEEK_END, &iSize))) return (hr); m_cbData = iSize.u.LowPart; } // Else there is nothing. else m_cbData = 0; // Save an addref'd copy of the stream. m_pIStream = pIStream; m_pIStream->AddRef(); // All access to data will be by memory provided. m_iType = STGIO_STREAM; goto ErrExit; } // If not on memory, we need a file to do a create/open. if (!szName || !*szName) { return (PostError(E_INVALIDARG)); } // Check for create of a new file. else if (fFlags & DBPROP_TMODEF_CREATE) { //<REVISIT_TODO>@future: This could chose to open the file in write through // mode, which would provide better Duribility (from ACID props), // but would be much slower.</REVISIT_TODO> // Create the new file, overwriting only if caller allows it. if ((m_hFile = WszCreateFile(szName, GENERIC_READ | GENERIC_WRITE, 0, 0, (fFlags & DBPROP_TMODEF_FAILIFTHERE) ? CREATE_NEW : CREATE_ALWAYS, 0, 0)) == INVALID_HANDLE_VALUE) { return (MapFileError(GetLastError())); } // Data will come from the file. m_iType = STGIO_HFILE; } // For open in read mode, need to open the file on disk. If opening a shared // memory view, it has to be opened already, so no file open. else if ((fFlags & DBPROP_TMODEF_WRITE) == 0) { // We have not opened the file nor loaded it as module _ASSERTE(m_hFile == INVALID_HANDLE_VALUE); _ASSERTE(m_hModule == NULL); // Open the file for read. Sharing is determined by caller, it can // allow other readers or be exclusive. DWORD dwFileSharingFlags = FILE_SHARE_DELETE; if (!(fFlags & DBPROP_TMODEF_EXCLUSIVE)) { dwFileSharingFlags |= FILE_SHARE_READ; #if !defined(DACCESS_COMPILE) && !defined(FEATURE_PAL) // PEDecoder is not defined in DAC // We prefer to use LoadLibrary if we can because it will share already loaded images (used for execution) // which saves virtual memory. We only do this if our caller has indicated that this PE file is trusted // and thus it is OK to do LoadLibrary (note that we still only load it as a resource, which mitigates // most of the security risk anyway). if ((fFlags & DBPROP_TMODEF_TRYLOADLIBRARY) != 0) { m_hModule = WszLoadLibraryEx(szName, NULL, LOAD_LIBRARY_AS_IMAGE_RESOURCE); if (m_hModule != NULL) { m_iType = STGIO_HMODULE; m_mtMappedType = MTYPE_IMAGE; // LoadLibraryEx returns 2 lowest bits indicating how the module was loaded m_pBaseData = m_pData = (void *)(((INT_PTR)m_hModule) & ~(INT_PTR)0x3); PEDecoder peDecoder; if (SUCCEEDED(peDecoder.Init( m_pBaseData, false)) && // relocated peDecoder.CheckNTHeaders()) { m_cbData = peDecoder.GetNTHeaders32()->OptionalHeader.SizeOfImage; } else { // PEDecoder failed on loaded library, let's backout all our changes to this object // and fall back to file mapping m_iType = STGIO_NODATA; m_mtMappedType = MTYPE_NOMAPPING; m_pBaseData = m_pData = NULL; FreeLibrary(m_hModule); m_hModule = NULL; } } } #endif //!DACCESS_COMPILE && !FEATURE_PAL } if (m_hModule == NULL) { // We didn't get the loaded module (we either didn't want to or it failed) HandleHolder hFile(WszCreateFile(szName, GENERIC_READ, dwFileSharingFlags, 0, OPEN_EXISTING, 0, 0)); if (hFile == INVALID_HANDLE_VALUE) return (MapFileError(GetLastError())); // Get size of file. m_cbData = ::SetFilePointer(hFile, 0, 0, FILE_END); // Can't read anything from an empty file. if (m_cbData == 0) return (PostError(CLDB_E_NO_DATA)); // Data will come from the file. m_hFile = hFile.Extract(); m_iType = STGIO_HFILE; } } ErrExit: // If we will ever write, then we need the buffer cache. if (fFlags & DBPROP_TMODEF_WRITE) { // Allocate a cache buffer for writing. if ((m_rgBuff = (BYTE *) AllocateMemory(m_iCacheSize)) == NULL) { Close(); return PostError(OutOfMemory()); } m_cbBuff = 0; } // Save flags for later. m_fFlags = fFlags; if ((szName != NULL) && (*szName != 0)) { WCHAR rcExt[_MAX_PATH]; SplitPath(szName, NULL, 0, NULL, 0, NULL, 0, rcExt, _MAX_PATH); if (SString::_wcsicmp(rcExt, W(".obj")) == 0) { m_FileType = FILETYPE_NTOBJ; } else if (SString::_wcsicmp(rcExt, W(".tlb")) == 0) { m_FileType = FILETYPE_TLB; } } // For auto map case, map the view of the file as part of open. if (m_bAutoMap && (m_iType == STGIO_HFILE || m_iType == STGIO_STREAM) && !(fFlags & DBPROP_TMODEF_CREATE)) { void * ptr; ULONG cb; if (FAILED(hr = MapFileToMem(ptr, &cb, pAttributes))) { Close(); return hr; } } return S_OK; } // StgIO::Open
Tga::Tga(const char* FilePath) { std::fstream hFile(FilePath, std::ios::in | std::ios::binary); if (!hFile.is_open()){throw std::invalid_argument("File Not Found.");} std::uint8_t Header[18] = {0}; std::vector<std::uint8_t> ImageData; static std::uint8_t DeCompressed[12] = {0x0, 0x0, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}; static std::uint8_t IsCompressed[12] = {0x0, 0x0, 0xA, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}; hFile.read(reinterpret_cast<char*>(&Header), sizeof(Header)); if (!std::memcmp(DeCompressed, &Header, sizeof(DeCompressed))) { BitsPerPixel = Header[16]; width = Header[13] * 0xFF + Header[12]; height = Header[15] * 0xFF + Header[14]; size = ((width * BitsPerPixel + 31) / 32) * 4 * height; if ((BitsPerPixel != 24) && (BitsPerPixel != 32)) { hFile.close(); throw std::invalid_argument("Invalid File Format. Required: 24 or 32 Bit Image."); } ImageData.resize(size); ImageCompressed = false; hFile.read(reinterpret_cast<char*>(ImageData.data()), size); } else if (!std::memcmp(IsCompressed, &Header, sizeof(IsCompressed))) { BitsPerPixel = Header[16]; width = Header[13] * 0xFF + Header[12]; height = Header[15] * 0xFF + Header[14]; size = ((width * BitsPerPixel + 31) / 32) * 4 * height; if ((BitsPerPixel != 24) && (BitsPerPixel != 32)) { hFile.close(); throw std::invalid_argument("Invalid File Format. Required: 24 or 32 Bit Image."); } RGB Pixel = {0}; int CurrentByte = 0; std::size_t CurrentPixel = 0; ImageCompressed = true; std::uint8_t ChunkHeader = {0}; int BytesPerPixel = (BitsPerPixel / 8); ImageData.resize(width * height * sizeof(RGB)); do { hFile.read(reinterpret_cast<char*>(&ChunkHeader), sizeof(ChunkHeader)); if(ChunkHeader < 128) { ++ChunkHeader; for(int I = 0; I < ChunkHeader; ++I, ++CurrentPixel) { hFile.read(reinterpret_cast<char*>(&Pixel), BytesPerPixel); ImageData[CurrentByte++] = Pixel.RGBA.B; ImageData[CurrentByte++] = Pixel.RGBA.G; ImageData[CurrentByte++] = Pixel.RGBA.R; if (BitsPerPixel > 24) ImageData[CurrentByte++] = Pixel.RGBA.A; } } else { ChunkHeader -= 127; hFile.read(reinterpret_cast<char*>(&Pixel), BytesPerPixel); for(int I = 0; I < ChunkHeader; ++I, ++CurrentPixel) { ImageData[CurrentByte++] = Pixel.RGBA.B; ImageData[CurrentByte++] = Pixel.RGBA.G; ImageData[CurrentByte++] = Pixel.RGBA.R; if (BitsPerPixel > 24) ImageData[CurrentByte++] = Pixel.RGBA.A; } } } while(CurrentPixel < (width * height)); } else { hFile.close(); throw std::invalid_argument("Invalid File Format. Required: 24 or 32 Bit TGA File."); } hFile.close(); this->Pixels = ImageData.data(); }