bool File::isRegular() const { struct stat fileStat; if(stat(fileName.c_str(), &fileStat) < 0) throw FileError(errno, "Could not check if file (%) is regular file.", fileName); if(S_ISREG(fileStat.st_mode)) return true; return false; }
sf::Texture AManager::getImage(std::string const &name) const { sf::Texture ret; std::map<std::string, sf::Texture>::iterator it = imageManager.find(name); if (it != imageManager.end()) ret = (imageManager[name]); else throw FileError("image", name); return ret; }
// empty the file void ArchiveData::ClearLogFile(void) { // append to global results file ofstream logstream; try { logstream.open(logFile,ios::trunc); if(!logstream.is_open()) FileError("File error opening log file",globalFile,"ArchiveData::ClearLogFile"); logstream.close(); if(logstream.bad()) FileError("File error closing log file",globalFile,"ArchiveData::ClearLogFile"); logStartTime=fmobj->CPUTime(); } catch(CommonException err) { // divert to standard output and try to continue cout << "# " << err.Message() << endl; if(logstream.is_open()) logstream.close(); } }
sf::Font AManager::getFont(std::string const &name) const { sf::Font ret; std::map<std::string, sf::Font>::iterator it = fontManager.find(name); if (it != fontManager.end()) ret = (fontManager[name]); else throw FileError("font", name); return (ret); }
void error(int lineno, char *line, char *cptr, char *msg, ...) { char sbuf[512]; va_list args; va_start(args, msg); vsprintf(sbuf, msg, args); va_end(args); FileError("%s", sbuf); read_errs++; }
NTL_START_IMPL void OpenWrite(ofstream& s, const char *name) { s.open(name, ios::out); if (!s) { FileError("write open failed"); } }
void File::create() { if(0 <= file) close(); if(exists()) return; file = open(fileName.c_str(), O_CREAT|O_WRONLY|O_TRUNC, 0600); if(file < 0) throw FileError(errno, "Could not create file %.", fileName); close(); }
const ClientPacket &DataBase::getClient(const std::string &login) { const std::string filename(this->DBDirectory + login.substr(0, 1) + "data" + this->DBExtension); if (!clients.openOCreate(filename)) throw FileError(); if (!searchClient(login)) throw NotExist(); return (pack); }
/** Konstruktor. * Otevre databazi pro zadany adresar (dir), predpoklada, ze se soubor databaze (name) * nachazi v aktualnim adresari. Pokud selze otevreni databaze (napriklad nekdo * zmenil prava souboru na 000), hodi vyjimku GdbmError. Databazi otevre jen * pro cteni. * Implicitne da ingore_hidden na true. */ DirectoryDatabase::DirectoryDatabase(const char *name) throw(FileError, GdbmError) { db_name = name; lock_name = name; lock_name = lock_name + "_gdbm_lock"; // je mozne, ze name bude obsahovat i cestu - zamek se tedy bude vytvaret v // miste, kde je ulozena databaze - nemohou tam byt dva soubory stejneho // jmena, takze je vse OK. #ifdef DD_DEBUG cout << getpid() << " - creating database " << db_name << endl; #endif ignore_hidden = true; num_of_deleted_items = 0; locked = false; /* vytvorime novou databazi, nastavime souboru pravo cteni a zapisu, * fatal_func() nechame defaultni (0) */ if (LockDatabase() == -1) { string msg; msg = "Nepodarilo se zamknout databazi. Program mozna nebyl naposledy ciste ukoncen. Zkontrolujte prosim, "; msg = msg + "jestli neexistuje soubor " + lock_name + " a smazte jej."; throw FileError(msg.c_str(), -1); } // --- zacatek KRITICKE SEKCE --- //pokud databaze neexistuje, vytvorime ji db_file = gdbm_open((char *)db_name.c_str(), GDBM_BLOCK_SIZE, GDBM_WRCREAT, S_IRUSR | S_IWUSR, 0); if (db_file == 0) throw GdbmError(); gdbm_close(db_file); if (UnlockDatabase() == -1) throw FileError("DirectoryDatabase(): Nepodarilo se odemknout databazi.", -1); // --- konec KRITICKE SEKCE --- }
bool File::exists() const { struct stat fileStat; int err = 0; if(stat(fileName.c_str(), &fileStat) < 0){ err = errno; if(err == ENOENT || err == ENOTDIR) return false; throw FileError(errno, "Could not check for the existence of file (%).", fileName); } return true; }
void WOFile::WriteBuffer(const void* pBuffer, unsigned int uiBufferSize) { if(!m_File) { throw FileError("NULL File pointer", EL_BAD, "WOFile::WriteBuffer", "File hasn't been opened!"); } fwrite(pBuffer, uiBufferSize, 1, m_File); if(ferror(m_File)) { throw FileWriteError(m_sFilename, EL_GENERAL, "WOFile::WriteBuffer", "Error while writing file:\r\n" + m_sFilename); } }
void File::openForRead() const { if(0 <= file && !writable) return; if(0 <= file) close(); file = open(fileName.c_str(), O_RDONLY, 0600); if(file < 0) throw FileError(errno, "Could not open file (%) for reading.", fileName); writable = false; eofbit = false; }
// empty the file void ArchiveData::WriteLogFile(const char *logLine,double *num) { // append to global results file ofstream logstream; try { logstream.open(logFile,ios::out | ios::app); if(!logstream.is_open()) FileError("File error opening log file",logFile,"ArchiveData::WriteLogFile"); double logWriteTime=fmobj->CPUTime(); logstream << logLine; double recentTime=logWriteTime-logStartTime; if(recentTime>1.e-4) { logstream << " (time: " << logWriteTime-logStartTime; if(num!=NULL) logstream << ", number: " << *num; logstream << ")"; } else { if(num!=NULL) logstream << "(number: " << *num << ")"; } logstream << endl; logStartTime=logWriteTime; if(logstream.bad()) FileError("File error writing line to log file",logFile,"ArchiveData::WriteLogFile"); logstream.close(); if(logstream.bad()) FileError("File error closing log file",logFile,"ArchiveData::WriteLogFile"); } catch(CommonException err) { // divert to standard output and try to continue cout << "# " << err.Message() << endl; cout << "# Log Line: " << logLine; if(num!=NULL) cout << "(number: " << *num << ")"; logstream << endl; if(logstream.is_open()) logstream.close(); } }
const ClientPacket &DataBase::addClient(const std::string &login, const std::string &passwd) { const std::string filename(this->DBDirectory + login.substr(0, 1) + "data" + this->DBExtension); if (!clients.openOCreate(filename)) throw FileError(); if (searchClient(login)) throw AlreadyExist(); pack.setValues(login, passwd); clients << pack; return (pack); }
int main(int argc, char* argv[]) /******************************/ { char tmpFile[L_tmpnam]; bool quiet; quiet = false; set_new_handler(outOfMemory); try { if( argc != 2 ) { if( argc == 3 && stricmp( argv[1], "/nologo" ) == 0 ) { quiet = true; argv[1] = argv[2]; } else { cerr << CVpackUsage; return 1; } } if( !quiet ) { cout << CVpackHeader << endl; } ::ConvertFName(argv[1]); ifstream fd(fName, ios::in | ios::binary); if ( !fd ) { throw FileError(fName); } tmpnam(tmpFile); CVpack packMaker(fd,tmpFile); //cerr << "calling packMaker.CreatePackExe()\n"; //cerr.flush(); packMaker.CreatePackExe(); //cout << "cvpack, packMaker.CreatePackExe() OK\n"; //cout.flush(); fd.close(); if ( remove(fName) ) { throw MiscError(strerror(errno)); } if ( rename(tmpFile,fName) ) { throw MiscError(strerror(errno)); } } catch (CVpackError& CVerr) { CVerr.ErrorPrint(); remove(tmpFile); exit(1); } return 0; }
void Path::readHomeDir() { std::string path(Glib::getenv("VLE_HOME")); if (not path.empty()) { if (fs::is_directory(path)) { m_home = path; } else { throw FileError(fmt(_( "Path: VLE_HOME '%1%' does not exist")) % path); } } else { m_home.clear(); } }
void OpenWrite(ofstream& s, const char *name, FileList& flist) { // post condition: file is successfully opened iff // name is added to flist (even if exception is thrown). // We do the AddFile first, since that can conceivably fail. flist.AddFile(name); s.open(name, ios::out); if (!s) { flist.RemoveLast(); FileError("write open failed"); } }
// Create global archive file void ArchiveData::CreateGlobalFile(void) { FILE *fp; char fline[1000]; GlobalQuantity *nextGlobal; // skip if none, but error if tried to define global quantities if(globalTime<0.) { globalTime=-1.; if(firstGlobal!=NULL) throw CommonException("<GlobalArchive> was used but never activated with a <GlobalArchiveTime> command.","ArchiveData::CreateGlobalFile"); return; } // get relative path name to the file globalFile=new char[strlen(outputDir)+strlen(archiveRoot)+8]; sprintf(globalFile,"%s%s.global",outputDir,archiveRoot); // create and open the file if((fp=fopen(globalFile,"w"))==NULL) goto abort; // write color strcpy(fline,"#setColor"); nextGlobal=firstGlobal; while(nextGlobal!=NULL) nextGlobal=nextGlobal->AppendColor(fline); strcat(fline,"\n"); if(fwrite(fline,strlen(fline),1,fp)!=1) goto abort; // write name strcpy(fline,"#setName"); nextGlobal=firstGlobal; while(nextGlobal!=NULL) nextGlobal=nextGlobal->AppendName(fline); strcat(fline,"\n"); if(fwrite(fline,strlen(fline),1,fp)!=1) goto abort; // close the file if(fclose(fp)!=0) goto abort; // section in output file PrintSection("ARCHIVED GLOBAL RESULTS"); cout << "Global data file: " << archiveRoot << ".global" << endl; cout << endl; return; abort: FileError("Global archive file creation failed",globalFile,"ArchiveData::CreateGlobalFile"); }
// Archive global results if it is time void ArchiveData::GlobalArchive(double atime) { // see if desired if(globalTime<0.) return; if(atime<nextGlobalTime) return; nextGlobalTime+=globalTime; // time in ms char fline[1000]; sprintf(fline,"%g",1000.*atime); // each global quantity GlobalQuantity *nextGlobal=firstGlobal; while(nextGlobal!=NULL) nextGlobal=nextGlobal->AppendQuantity(fline); // append to global results file ofstream global; try { global.open(globalFile,ios::out | ios::app); if(!global.is_open()) FileError("File error opening global results",globalFile,"ArchiveData::GlobalArchive"); global << fline << endl; if(global.bad()) FileError("File error writing global results",globalFile,"ArchiveData::GlobalArchive"); global.close(); if(global.bad()) FileError("File error closing global results",globalFile,"ArchiveData::GlobalArchive"); } catch(CommonException err) { // divert to standard output and try to continue cout << "# " << err.Message() << endl; cout << "# Data: " << fline << endl; if(global.is_open()) global.close(); } }
void WOFile::Open() { if(m_sFilename.empty()) { throw FileError("NULL Filename", EL_BAD, "WOFile::Open", "Filename is NULL!"); } Close(); m_File = fopen(m_sFilename.c_str(), "wb"); if(!m_File) { throw FileNotFound(m_sFilename.c_str()); } }
Loader::Loader() { QFile file(Lotto::sampleFile.c_str()); file.open(QFile::ReadOnly); if (file.exists() && file.isReadable()) { QByteArray allFile = file.readAll(); std::string data = allFile.data(); for (unsigned int i = 0; i < data.length(); i++) { if (data[i] == '#' || data[i] == '\n' || data[i] == ' ' || data[i] == '\r') { while (data[i] != '\n') { i++; } continue; } try { int id = getNumber(i, data); std::string date = getData(i, data); int *numbers = getNumbers(i, data); Sample* s = new Sample(id, date, numbers); i--; list.push_front(s); if (debug) { std::cout << *s; } } catch (NumberException &e) { std::cout << "NumberExceptionError\nLine: " << __LINE__ << "\nFile: " << __FILE__ << std::endl; throw; } } } else { throw FileError(); } }
void File::rename(const Str & name) { if(0 <= file) close(); String oldFileName(fileName); // char buf[PATH_MAX]; // String cwd(char *getcwd(buf, PATH_MAX)); fileName.assign(name); int fn = ::rename(oldFileName.c_str(), fileName.c_str()); if(fn < 0){ int errNo = errno; fileName = move_cast(oldFileName); throw FileError(errNo, "Could not rename file % to %.", fileName, name); } }
void ROFile::ReadBuffer(void* pBuffer, unsigned int uiBufferSize) { if(!m_File) { throw FileError("NULL File pointer", EL_BAD, "ROFile::ReadBuffer", "File hasn't been opened!"); } unsigned int rc = fread(pBuffer, uiBufferSize, 1, m_File); if(feof(m_File)) { throw FileEOF(m_sFilename.c_str(), rc); } else if(ferror(m_File)) { throw FileReadError(m_sFilename.c_str(), EL_BAD, "ROFile::ReadBuffer", "Error while reading file:\r\n" + m_sFilename); } }
/** * Based on stackoverflow answer: * http://stackoverflow.com/questions/575328/fcntl-lockf-which-is-better-to-use-for-file-locking?answertab=active#tab-top * It says: * Locking in unix/linux is by default advisory.... * Also says: * Linux does support mandatory locking, but only if your file system is * mounted with the option on and the file special attributes set. * * length is the number of bytes to lock from the current position; 0 means infinity */ void File::lock(off_t length) { if(file < 0 || !writable) openForWrite(); if(lockf(file, F_TLOCK, length) < 0) throw FileError(errno, "Failed to lock file %.", fileName); locked = true; /* // alternate implementation (void)length; if(0 < file) close(); file = open(fileName, O_RDWR|O_CREAT|O_EXCL, 0600); if(file < 0) throw FileError(errno, "Failed to open file % in exclusive open mode.", fileName); writable = true; eofbit = false; locked = true; */ }
/*--- Prepare download, then issue the FTP commands ---*/ void Downloader::DownloadFile(QString dir, QString file) { qDebug() << "Downloader::DownloadFile " + dir + file; // Data QUrl fileUrl(*baseUrl); QNetworkRequest r; QDir tempDir("."); // Setup downloadedSize = 0; lastDownloadedSize = 0; currentFtpDir = dir; currentFtpFile = file; currentFile = new QFile(currentFtpDir + currentFtpFile); fileUrl.setPath(FTP_UPDATE_ROOT + currentFtpDir + currentFtpFile); r.setUrl(fileUrl); // Local file preparation if (currentFtpDir.length() > 0) { tempDir.mkpath(currentFtpDir); } if (currentFtpFile.length() > 0 && currentFile->exists()) { currentFile->remove(); } currentFile->open(QIODevice::WriteOnly); // Download command bDownloading = true; reply = ftp->get(r); reply->setReadBufferSize(FTP_PART_SIZE); connect(reply, SIGNAL(readyRead()), this, SLOT(FilePart())); connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(FileError(QNetworkReply::NetworkError))); // Timers timeoutTimer->setSingleShot(true); timeoutTimer->start(FTP_TIMEOUT); }
/** * Load Edges from file */ void LoadEdge(char* path){ char fullPath[1000]; strcpy(fullPath,path); strcat(fullPath,EDGE_INPUT_FILE); int pointerFile = open(fullPath, O_RDONLY); if (pointerFile == -1) FileError(EDGE_INPUT_FILE "can not open!"); int size = read(pointerFile, readBuffer, nowSize); if (readBuffer[size - 1] != '\n') readBuffer[size++] = '\n'; readBuffer[size++] = '\0'; int index_size = (originEdgeNumber << 1) * sizeof(int); pre = (int*)malloc(index_size); other = (int*)malloc(index_size); thisSide=(int*)malloc(index_size); cost=(int*)malloc(index_size); last=(int*)malloc(index_size); memset(last,255,index_size); int i, j, k = -1; int r1, r2, l; t = readBuffer; while (*t != '\0') { j = P_ParseInteger(); ++t; if (j > k) k = j; r1 = P_ParseInteger(); ++t; r2 = P_ParseInteger(); ++t; l = P_ParseInteger(); ++t; pre[j]=last[r1]; last[r1]=j; cost[j]=l; other[j]=r2; thisSide[j]=r1; } edgeNumber = k + 1; close(pointerFile); }
/** Function to Dump E32 Image. @param afileName - E32 Image File name @return 1 on success, otherwise throw error @internalComponent @released */ int FileDump::DumpE32Image(const char* afileName) { E32ImageFile *aE32Imagefile=new E32ImageFile(); TInt result = aE32Imagefile->Open(afileName); if (result > 0) return 1; else if (result == KErrCorrupt || result == KErrNotSupported) { throw InvalidE32ImageError(INVALIDE32IMAGEERROR, (char *)afileName); } else if (result != 0) { throw FileError(FILEREADERROR, (char *)afileName); } int dumpOptions=iParameterListInterface->DumpOptions(); aE32Imagefile->Dump((TText*)afileName, dumpOptions); delete aE32Imagefile; return KErrNone; }
void DataBase::getContactList(const ClientPacket &pack, std::list<std::string> &list) { const std::string login = pack.getLogin(); const std::string fname(this->DBDirectory + login.substr(0, 1) + "friends" + this->DBExtension); const std::string cname(this->DBDirectory + login.substr(0, 1) + "data" + this->DBExtension); if (login == "" || !clients.openFile(cname) || !searchClient(login)) throw NotExist(); if (!friends.openOCreate(fname)) throw FileError(); // list.clear(); // clear la liste ? while (friends.good() && !friends.eof()) { friends >> fpack; if (!fpack.isErased() && fpack.getOrig() == login) list.push_back(fpack.getFLogin()); } }
void CloseWrite(ofstream& s) { s.close(); if (s.fail()) FileError("close failed"); }
int game::SaveGame(char *saveFile, int autosave, signed char baseGame) { void* extraMemory = ALLOC(50000); memset(extraMemory, 0, 50000u); baseGame = 0; gpAdvManager->DemobilizeCurrHero(); char path[100]; char v9[100]; if(autosave) { if(!xIsExpansionMap || baseGame) { sprintf(path, "%s.GM1", saveFile); } else { sprintf(path, "%s.GX1", saveFile); } } else { sprintf(path, saveFile); } sprintf(v9, "%s%s", ".\\GAMES\\", &path); if(strnicmp(path, "AUTOSAVE", 8) && strnicmp(path, "PLYREXIT", 8)) strcpy(gpGame->lastSaveFile, saveFile); int fd = open(tmpFileName, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, S_IWRITE); if ( fd == -1 ) FileError("tmp"); _write(fd, &this->map.width, 4); _write(fd, &this->map.height, 4); _write(fd, &this->mapHeader, 420); _write(fd, &this->field_44D, 65); _write(fd, this, 2); _write(fd, &giMonthType, 1); _write(fd, &giMonthTypeExtra, 1); _write(fd, &giWeekType, 1); _write(fd, &giWeekTypeExtra, 1); _write(fd, cPlayerNames, 126); char buf[100]; gpAdvManager->PurgeMapChangeQueue(); _write(fd, &giMapChangeCtr, 4); GenerateStandardFileName(this->lastSaveFile, buf); _write(fd, &this->numPlayers, 1); int v14 = giCurPlayer; _write(fd, &v14, 1); _write(fd, &this->couldBeNumDefeatedPlayers, 1); _write(fd, this->playerDead, 6); char playerAlive[6]; for (int i = 0; i < 6; ++i) { playerAlive[i] = gbHumanPlayer[i]; if(this->playerDead[i]) playerAlive[i] = 0; } _write(fd, playerAlive, 6); _write(fd, &this->day, 2); _write(fd, &this->week, 2); _write(fd, &this->month, 2); for(int i = 0; i < 6; ++i ) this->players[i].Write(fd); _write(fd, &this->numObelisks, 1); _write(fd, this->relatedToHeroForHireStatus, 54); _write(fd, this->castles, 7200); _write(fd, this->field_2773, 72); _write(fd, this->field_27BB, 9); _write(fd, this->mines, 1008); _write(fd, this->field_60A6, 144); _write(fd, this->artifactGeneratedRandomly, 103); _write(fd, this->boats, 384); _write(fd, this->boatBuilt, 48); _write(fd, this->obeliskVisitedMasks, 48); _write(fd, &this->field_6395, 1); _write(fd, &this->field_6396, 1); _write(fd, &this->field_6397, 1); _write(fd, this->currentRumor, 301); _write(fd, this->field_637D, 24); _write(fd, &this->numRumors, 4); _write(fd, this->rumorIndices, 2 * this->numRumors); _write(fd, &this->numEvents, 4); _write(fd, this->eventIndices, 2 * this->numEvents); _write(fd, &this->field_657B, 4); _write(fd, this->_D, 2 * this->field_657B); _write(fd, &iMaxMapExtra, 4); for(int i = 1; i < iMaxMapExtra; ++i) { _write(fd, &pwSizeOfMapExtra[i], 2); if(ppMapExtra[i]) _write(fd, ppMapExtra[i], pwSizeOfMapExtra[i]); else _write(fd, extraMemory, pwSizeOfMapExtra[i]); } _write(fd, mapRevealed, MAP_HEIGHT * MAP_WIDTH); this->map.Write(fd); _close(fd); FREE(extraMemory); unsigned char dat[1000000]; fd = _open(tmpFileName, O_BINARY); lseek(fd, 0, SEEK_END); int sz = tell(fd); lseek(fd, 0, SEEK_SET); read(fd, dat, sz); close(fd); remove(tmpFileName); const xml_schema::base64_binary datbin(dat, sz); std::ofstream os(v9); ironfist_map::map_t m(datbin); for(int i = 0; i < ELEMENTS_IN(this->heroes); i++) { m.hero().push_back(WriteHeroXML(&this->heroes[i])); } m.script(GetScriptContents()); WriteMapVariablesXML(m); xml_schema::namespace_infomap infomap; infomap[""].name = "ironfist_map"; infomap[""].schema = "map_xml.xsd"; ironfist_map::map(os, m, infomap); return 1; }