static int onNewFileAdded( vlc_object_t *p_this, char const *psz_var, vlc_value_t oldval, vlc_value_t newval, void *p_data ) { (void)p_this; services_discovery_t *p_sd = p_data; services_discovery_sys_t *p_sys = p_sd->p_sys; (void)psz_var; (void)oldval; char* psz_file = newval.psz_string; if( !psz_file || !*psz_file ) return VLC_EGENERIC; char* psz_uri = make_URI( psz_file, "file" ); input_item_t* p_item = input_item_New( psz_uri, NULL ); if( p_sys->i_type == Picture ) { if( fileType( p_sd, psz_file ) == Picture ) { formatSnapshotItem( p_item ); services_discovery_AddItem( p_sd, p_item, NULL ); msg_Dbg( p_sd, "New snapshot added : %s", psz_file ); } } else if( p_sys->i_type == Audio ) { if( fileType( p_sd, psz_file ) == Audio ) { services_discovery_AddItem( p_sd, p_item, NULL ); msg_Dbg( p_sd, "New recorded audio added : %s", psz_file ); } } else if( p_sys->i_type == Video ) { if( fileType( p_sd, psz_file ) == Video || fileType( p_sd, psz_file ) == Unknown ) { services_discovery_AddItem( p_sd, p_item, NULL ); msg_Dbg( p_sd, "New recorded video added : %s", psz_file ); } } vlc_gc_decref( p_item ); free( psz_uri ); return VLC_SUCCESS; }
Boolean shelf_push(int i, Boolean absolute, Boolean pushdir) { FilePtr file = dirFile(shelfdir, i); String action; char path1[MAXPATHLEN+1], path2[MAXPATHLEN+1]; root_modified = cur_modified = shelf_modified = cur_changed = False; if (file) if (!((action = push_action(fileType(file))) && *action) && S_ISDIR(fileStats(file)->st_mode)) { return cur_chdir(resolve(path1, pathname(path2, dirName(shelfdir), fileName(file)))); } else { Boolean ret = filePush(shelfdir, i, (pushdir && (fileStats(file)->st_mode & (S_IXUSR | S_IXGRP | S_IXOTH)))? dirName(curdir):NULL, absolute, True); update(); return ret; } else return False; }
int fileInteg( char *fname, char *fsave, int StartPP, int EndPP) { int outSize; float *outData; FILE *file_ptr; FILE *save_ptr; struct SHM_PARAM param; int filetype; //-------- Read File Pointer if(( filetype = fileType(fname)) == 0){ return(-1);} if((file_ptr = fopen(fname, "r")) == NULL){ return(-1);} // Open input file fread(¶m, sizeof(struct SHM_PARAM), 1, file_ptr); fclose(file_ptr); outSize = filetype * param.num_ch * sizeof(float); if( outSize == 0){ printf("Invalid File Type!\n"); return(-1); } outData = (float *)malloc( outSize ); memset(outData, 0, outSize); specTimeInteg( fname, filetype, StartPP, EndPP, outData ); save_ptr = fopen(fsave, "w"); fwrite( outData, outSize, 1, save_ptr); fclose( save_ptr); free(outData); return(outSize); }
static RBinInfo *info(RBinFile *bf) { RBinInfo *ret = R_NEW0 (RBinInfo); if (!ret) { return NULL; } const char *ft = fileType (r_buf_get_at (bf->buf, NRO_OFF (magic), NULL)); if (!ft) { ft = "nro"; } ret->file = strdup (bf->file); ret->rclass = strdup (ft); ret->os = strdup ("switch"); ret->arch = strdup ("arm"); ret->machine = strdup ("Nintendo Switch"); ret->subsystem = strdup (ft); if (!strncmp (ft, "nrr", 3)) { ret->bclass = strdup ("program"); ret->type = strdup ("EXEC (executable file)"); } else if (!strncmp (ft, "nro", 3)) { ret->bclass = strdup ("object"); ret->type = strdup ("OBJECT (executable code)"); } else { // mod ret->bclass = strdup ("library"); ret->type = strdup ("MOD (executable library)"); } ret->bits = 64; ret->has_va = true; ret->has_lit = true; ret->big_endian = false; ret->dbg_info = 0; ret->dbg_info = 0; return ret; }
void Operation::cleanup() { if(fileType() == File) { if(!QFile(dataFilename()).remove()) throwWarning(QObject::tr("Unable to remove temporary file %1").arg(dataFilename())); } }
bool DatIndexWriter::write(uint p_amount) { for (uint i = 0; i < p_amount; i++) { ssize_t bytesWritten; // First write categories, one at a time if (m_categoriesWritten < m_index.numCategories()) { auto category = m_index.category(m_categoriesWritten); auto parent = category->parent(); wxScopedCharBuffer nameBuffer = category->name().ToUTF8(); // Fixed-width fields DatIndexCategoryFields fields; fields.parent = (parent ? parent->index() : -1); fields.nameLength = nameBuffer.length(); bytesWritten = m_file.Write(&fields, sizeof(fields)); if (bytesWritten < sizeof(fields)) { return false; } // Name bytesWritten = m_file.Write(nameBuffer, fields.nameLength); if (bytesWritten < fields.nameLength) { return false; } // Increase the counter m_categoriesWritten++; } // Then, write entries one at a time (note the 'else') else if (m_entriesWritten < m_index.numEntries()) { auto entry = m_index.entry(m_entriesWritten); auto category = entry->category(); auto nameBuffer = entry->name().ToUTF8(); // Fixed-width fields DatIndexEntryFields fields; fields.category = category->index(); fields.baseId = entry->baseId(); fields.fileId = entry->fileId(); fields.mftEntry = entry->mftEntry(); fields.fileType = entry->fileType(); fields.nameLength = nameBuffer.length(); bytesWritten = m_file.Write(&fields, sizeof(fields)); if (bytesWritten < sizeof(fields)) { return false; } // Name bytesWritten = m_file.Write(nameBuffer, fields.nameLength); if (bytesWritten < fields.nameLength) { return false; } // Increase the counter m_entriesWritten++; } // Both done = ditch this loop else { break; } } // Remove dirty flag if everything is saved if (this->isDone()) { m_index.setDirty(false); } return true; }
std::string CollisionModel::toXML(const std::string& basePath, const std::string& filename, int tabs) { std::stringstream ss; std::string t = "\t"; std::string pre = ""; for (int i = 0; i < tabs; i++) { pre += "\t"; } ss << pre << "<CollisionModel"; if (getVisualization()->usedBoundingBoxVisu()) { ss << " BoundingBox='true'"; } ss << ">\n"; std::string fileType("unknown"); if (visualization) { fileType = visualization->getType(); } else if (modelVisualization) { fileType = modelVisualization->getType(); } if (!filename.empty()) { std::string tmpFilename = filename; BaseIO::makeRelativePath(basePath, tmpFilename); ss << pre << t << "<File type='" << fileType << "'>" << tmpFilename << "</File>\n"; } if (visualization && visualization->primitives.size() != 0) { ss << pre << "\t<Primitives>\n"; std::vector<Primitive::PrimitivePtr>::const_iterator it; for (it = visualization->primitives.begin(); it != visualization->primitives.end(); it++) { ss << (*it)->toXMLString(tabs + 1); } ss << pre << "\t</Primitives>\n"; } ss << pre << "</CollisionModel>\n"; return ss.str(); }
static Boolean dir_is_drop_target(DirPtr dir, int i) { FilePtr file = dirFile(dir, i); String action = drop_action(fileType(file)); return i == NONE || file && (action && *action || S_ISDIR(fileStats(file)->st_mode) || (fileStats(file)->st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))); }
KstDataSourceConfigWidget* KstDataSource::configWidget() const { KstDataSourceConfigWidget *w = configWidgetForSource(_filename, fileType()); if (w) { // FIXME: what to do here? This is ugly, but the method is const and we // can't put a const shared pointer in the config widget. Fix for // Kst 2.0 by making this non-const? w->_instance = const_cast<KstDataSource*>(this); } return w; }
/* * sysGetSendFilesV2() * * This function figures out where to find files to send to another system. */ char sysGetSendFilesV2(MenuId id, char *name, struct fl_send *sendWhat) { strCpy(sendWhat->snArea.naDirname, name); MSDOSparse(sendWhat->snArea.naDirname, &sendWhat->snArea.naDisk); if (fileType(sendWhat->snArea.naDirname, sendWhat->snArea.naDisk) == NO_IDEA) { if (SysopGetYesNo(id, "", "Neither file nor directory found. Send anyways")) return TRUE; return FALSE; } return TRUE; }
// https://wicg.github.io/entries-api/#dom-filesystemdirectoryentry-getfile // https://wicg.github.io/entries-api/#dom-filesystemdirectoryentry-getdirectory void DOMFileSystem::getEntry(ScriptExecutionContext& context, FileSystemDirectoryEntry& directory, const String& virtualPath, const FileSystemDirectoryEntry::Flags& flags, GetEntryCallback&& completionCallback) { ASSERT(&directory.filesystem() == this); if (!isValidVirtualPath(virtualPath)) { callOnMainThread([completionCallback = WTFMove(completionCallback)] { completionCallback(Exception { TypeMismatchError, "Path is invalid"_s }); }); return; } if (flags.create) { callOnMainThread([completionCallback = WTFMove(completionCallback)] { completionCallback(Exception { SecurityError, "create flag cannot be true"_s }); }); return; } auto resolvedVirtualPath = resolveRelativeVirtualPath(directory.virtualPath(), virtualPath); ASSERT(resolvedVirtualPath[0] == '/'); auto fullPath = evaluatePath(resolvedVirtualPath); if (fullPath == m_rootPath) { callOnMainThread([this, context = makeRef(context), completionCallback = WTFMove(completionCallback)]() mutable { completionCallback(Ref<FileSystemEntry> { root(context) }); }); return; } m_workQueue->dispatch([this, context = makeRef(context), fullPath = crossThreadCopy(fullPath), resolvedVirtualPath = crossThreadCopy(resolvedVirtualPath), completionCallback = WTFMove(completionCallback)]() mutable { auto entryType = fileType(fullPath); callOnMainThread([this, context = WTFMove(context), resolvedVirtualPath = crossThreadCopy(resolvedVirtualPath), entryType, completionCallback = WTFMove(completionCallback)]() mutable { if (!entryType) { completionCallback(Exception { NotFoundError, "Cannot find entry at given path"_s }); return; } switch (entryType.value()) { case FileMetadata::Type::Directory: completionCallback(Ref<FileSystemEntry> { FileSystemDirectoryEntry::create(context, *this, resolvedVirtualPath) }); break; case FileMetadata::Type::File: completionCallback(Ref<FileSystemEntry> { FileSystemFileEntry::create(context, *this, resolvedVirtualPath) }); break; default: completionCallback(Exception { NotFoundError, "Cannot find entry at given path"_s }); break; } }); }); }
/* * ValidArea() * * This will validate an area choice the system operator has made. */ char ValidArea(char *area) { char drive, *work, c; MSDOSparse(area, &drive); c = fileType(area, drive); if (!CheckArea(NO_MENU, c, &drive, area)) return FALSE; work = GetDynamic(strlen(area) + 5); sprintf(work, "%c:%s", drive, area); strcpy(area, work); free(work); return TRUE; }
void Mesh_Specification::Global_Data_Size( long long Num_Nodes_Global, long long Num_Elems_Global, long long Num_Elem_Blks, long long Num_Node_Sets, long long Num_Side_Sets, long long Num_Total_Procs, long long Rank) /*****************************************************************************/ { msia[NUM_NODES_GLOBAL] = Num_Nodes_Global; msia[NUM_ELEMS_GLOBAL] = Num_Elems_Global; msia[NUM_ELM_BLKS_GLOBAL] = Num_Elem_Blks; msia[NUM_NODE_SETS_GLOBAL] = Num_Node_Sets; msia[NUM_SIDE_SETS_GLOBAL] = Num_Side_Sets; msia[NUM_TOTAL_PROC] = Num_Total_Procs; msia[PROC_ID] = Rank; msia[NUM_PROC_IN_FILE] = 1; std::string fileType("p"); file_type = fileType; Allocate_Global_Data(); }
void BCLFileReference::writeValues(QDomDocument& doc, QDomElement& element) const { if (m_usageType == "script" && !m_softwareProgram.empty() && !m_softwareProgramVersion.empty()){ QDomElement versionElement = doc.createElement("version"); element.appendChild(versionElement); QDomElement softwareProgramElement = doc.createElement("software_program"); versionElement.appendChild(softwareProgramElement); softwareProgramElement.appendChild(doc.createTextNode(toQString(m_softwareProgram))); QDomElement softwareProgramVersionElement = doc.createElement("identifier"); versionElement.appendChild(softwareProgramVersionElement); softwareProgramVersionElement.appendChild(doc.createTextNode(toQString(m_softwareProgramVersion))); if (m_minCompatibleVersion){ QDomElement minCompatibleVersionElement = doc.createElement("min_compatible"); versionElement.appendChild(minCompatibleVersionElement); minCompatibleVersionElement.appendChild(doc.createTextNode(toQString(m_minCompatibleVersion->str()))); } if (m_maxCompatibleVersion){ QDomElement maxCompatibleVersionElement = doc.createElement("max_compatible"); versionElement.appendChild(maxCompatibleVersionElement); maxCompatibleVersionElement.appendChild(doc.createTextNode(toQString(m_maxCompatibleVersion->str()))); } } QDomElement fileNameElement = doc.createElement("filename"); element.appendChild(fileNameElement); fileNameElement.appendChild(doc.createTextNode(toQString(fileName()))); // careful to write out function result instead of member QDomElement fileTypeElement = doc.createElement("filetype"); element.appendChild(fileTypeElement); fileTypeElement.appendChild(doc.createTextNode(toQString(fileType()))); // careful to write out function result instead of member QDomElement usageTypeElement = doc.createElement("usage_type"); element.appendChild(usageTypeElement); usageTypeElement.appendChild(doc.createTextNode(toQString(m_usageType))); QDomElement checksumElement = doc.createElement("checksum"); element.appendChild(checksumElement); checksumElement.appendChild(doc.createTextNode(toQString(m_checksum))); }
Boolean cur_drop(int i, int op, SelPtr sel, Boolean absolute, Boolean dirtarget) { Boolean ret; FilePtr file = dirFile(curdir, i); String action; char path[MAXPATHLEN+1]; if (i != NONE) if (!((action = drop_action(fileType(file))) && *action) && S_ISDIR(fileStats(file)->st_mode)) ret = fileMov(op)(sel, pathname(path, dirName(curdir), fileName(file)), absolute); else ret = fileDrop(curdir, i, sel, absolute, dirtarget, False); else ret = fileMov(op)(sel, dirName(curdir), absolute); update(); return ret; }
Boolean cur_push(int i, Boolean absolute, Boolean pushdir) { FilePtr file = dirFile(curdir, i); String action; char path1[MAXPATHLEN+1], path2[MAXPATHLEN+1]; root_modified = cur_modified = shelf_modified = cur_changed = False; if (file) if (!((action = push_action(fileType(file))) && *action) && S_ISDIR(fileStats(file)->st_mode)) { return cur_chdir(shortestpath(path1, pathname(path2, dirName(curdir), fileName(file)))); } else { Boolean ret = filePush(curdir, i, NULL, absolute, False); update(); return ret; } else return False; }
void RadiantFileTypeRegistry::addType(const std::string& moduleType, const std::string& moduleName, const FileTypePattern& type) { // Create the association between module name and file type pattern ModuleFileType fileType(moduleName, type); // If there is already a list for this type, add our new type to the // back of it TypeListMap::iterator i = _typeLists.find(moduleType); if (i != _typeLists.end()) { i->second->push_back(fileType); } else { // Otherwise create a new type list and add it to our map ModuleTypeListPtr newList(new ModuleTypeList()); newList->push_back(fileType); _typeLists.insert(TypeListMap::value_type(moduleType, newList)); } }
/* * sysSendFiles() * * This is the system dep stuff for sending files. */ void sysSendFiles(struct fl_send *sendWhat) { char temp[100], *last; label mask; strCpy(temp, sendWhat->snArea.naDirname); switch (fileType(sendWhat->snArea.naDirname, sendWhat->snArea.naDisk)) { case IS_DIR: strCpy(mask, ALL_FILES); break; case SINGLE_FILE: case AMB_FILE: if ((last = strrchr(temp, '\\')) == NULL) { strCpy(mask, temp); temp[0] = 0; } else { strCpy(mask, last + 1); if (last != temp) *last = 0; else *(last + 1) = 0; } break; case NO_IDEA: default: sprintf(temp, "Send File: Couldn't do anything with '%s'.", sendWhat->snArea.naDirname); netResult(temp); return; } if (!realSetSpace(toUpper(sendWhat->snArea.naDisk)-'A', temp)) { sprintf(msgBuf.mbtext, "Send file: Don't know what to do with %c:%s.", sendWhat->snArea.naDisk, temp); netResult(msgBuf.mbtext); } else wildCard(netSendFile, mask, "", WC_NO_COMMENTS); homeSpace(); }
/* * goodArea() * * This will get a valid path from the sysop. Drive should be set already. */ static goodArea(MenuId id, char *prompt, char *dir, char *drive) { int c; char dir_x[150], *dft; while (TRUE) { if (roomBuf.rbflags.ISDIR) dft = FindDirName(thisRoom); else dft = ourHomeSpace; if (!getXInternal(id, prompt, dir_x, 149, dft, dft)) return FALSE; MSDOSparse(dir_x, drive); c = fileType(dir_x, *drive); if (CheckArea(id, c, drive, dir_x)) { strCpy(dir, dir_x); return TRUE; } } }
bool EventFileRefFilter::Filter( const entry_ref* ref, BNode* node, struct stat_beos* st, const char* filetype ) { BString fileType( filetype ); BDirectory testDir( ref ); BEntry tempEntry; BNode tempNode; char buffer[ B_MIME_TYPE_LENGTH ]; // All directories are allowed - else the user won't be able to travel if ( testDir.InitCheck() == B_OK ) { return true; } // All Event files are allowed if ( fileType.IFindFirst( kEventFileMIMEType ) == 0 ) { return true; } // Symlinks are traversed and allowed only if they point to audio file while ( fileType.IFindFirst( "application/x-vnd.Be-symlink" ) == 0 ) { if ( ( B_OK == tempEntry.SetTo( ref, true ) ) && // Find the entry referenced by symlink ( B_OK == tempNode.SetTo( &tempEntry ) ) && // Access the attributes (needed to read file type) ( 0 != tempNode.ReadAttr( "BEOS:TYPE", B_STRING_TYPE, 0, buffer, 255 ) ) && ( NULL != fileType.SetTo( buffer ) ) && // This check is really unnecessary ( fileType.IFindFirst( kEventFileMIMEType ) == 0 ) ) { return true; } } return false; } // <-- end of function EventFileRefFilter::Filter
// ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- int32_t VtkStructuredPointsReader:: readFile() { int32_t err = 0; DataContainer::Pointer volDc = getDataContainerArray()->getDataContainer(getVolumeDataContainerName()); AttributeMatrix::Pointer volAm = volDc->getAttributeMatrix(getCellAttributeMatrixName()); DataContainer::Pointer vertDc = getDataContainerArray()->getDataContainer(getVertexDataContainerName()); AttributeMatrix::Pointer vertAm = vertDc->getAttributeMatrix(getVertexAttributeMatrixName()); std::ifstream in(getInputFile().toLatin1().constData(), std::ios_base::in | std::ios_base::binary); if (!in.is_open()) { QString msg = QObject::tr("Error opening output file '%1'").arg(getInputFile()); setErrorCondition(-61003); notifyErrorMessage(getHumanLabel(), msg, getErrorCondition()); return -100; } QByteArray buf(kBufferSize, '\0'); char* buffer = buf.data(); err = readLine(in, buffer, kBufferSize); // Read Line 1 - VTK Version Info err = readLine(in, buffer, kBufferSize); // Read Line 2 - User Comment setComment(QString(buf)); err = readLine(in, buffer, kBufferSize); // Read Line 3 - BINARY or ASCII QString fileType(buf); if (fileType.startsWith("BINARY") == true) { setFileIsBinary(true); } else if (fileType.startsWith("ASCII") == true) { setFileIsBinary(false); } else { QString ss = QObject::tr("The file type of the VTK legacy file could not be determined. It should be 'ASCII' or 'BINARY' and should appear on line 3 of the file"); setErrorCondition(-61004); notifyErrorMessage(getHumanLabel(), ss, getErrorCondition()); return getErrorCondition(); } // Read Line 4 - Type of Dataset err = readLine(in, buffer, kBufferSize); QList<QByteArray> words = buf.split(' '); if (words.size() != 2) { QString ss = QObject::tr("Error reading the type of data set. Was expecting 2 words but got %1").arg(QString(buf)); setErrorCondition(-61005); notifyErrorMessage(getHumanLabel(), ss, getErrorCondition()); return getErrorCondition(); } QString dataset(words.at(1)); dataset = dataset.trimmed(); setDatasetType(dataset); // Should be STRUCTURED_POINTS bool ok = false; err = readLine(in, buffer, kBufferSize); // Read Line 5 which is the Dimension values // But we need the 'extents' which is one less in all directions (unless dim=1) QVector<size_t> dims(3, 0); QList<QByteArray> tokens = buf.split(' '); dims[0] = tokens[1].toInt(&ok, 10); dims[1] = tokens[2].toInt(&ok, 10); dims[2] = tokens[3].toInt(&ok, 10); QVector<size_t> tDims(3, 0); tDims[0] = dims[0]; tDims[1] = dims[1]; tDims[2] = dims[2]; vertAm->setTupleDimensions(tDims); vertDc->getGeometryAs<ImageGeom>()->setDimensions(dims.data()); tDims[0] = dims[0] - 1; tDims[1] = dims[1] - 1; tDims[2] = dims[2] - 1; volAm->setTupleDimensions(tDims); volDc->getGeometryAs<ImageGeom>()->setDimensions(tDims.data()); err = readLine(in, buffer, kBufferSize); // Read Line 7 which is the Scaling values tokens = buf.split(' '); float resolution[3]; resolution[0] = tokens[1].toFloat(&ok); resolution[1] = tokens[2].toFloat(&ok); resolution[2] = tokens[3].toFloat(&ok); volDc->getGeometryAs<ImageGeom>()->setResolution(resolution); vertDc->getGeometryAs<ImageGeom>()->setResolution(resolution); err = readLine(in, buffer, kBufferSize); // Read Line 6 which is the Origin values tokens = buf.split(' '); float origin[3]; origin[0] = tokens[1].toFloat(&ok); origin[1] = tokens[2].toFloat(&ok); origin[2] = tokens[3].toFloat(&ok); volDc->getGeometryAs<ImageGeom>()->setOrigin(origin); vertDc->getGeometryAs<ImageGeom>()->setOrigin(origin); // Read the first key word which should be POINT_DATA or CELL_DATA err = readLine(in, buffer, kBufferSize); // Read Line 6 which is the first type of data we are going to read tokens = buf.split(' '); QString word = QString(tokens[0]); int32_t npts = 0, ncells = 0; int32_t numPts = 0; if ( word.startsWith("CELL_DATA") ) { DataContainer::Pointer m = getDataContainerArray()->getDataContainer(getVolumeDataContainerName()); m_CurrentAttrMat = m->getAttributeMatrix(getCellAttributeMatrixName()); ncells = tokens[1].toInt(&ok); if (m_CurrentAttrMat->getNumTuples() != ncells) { setErrorCondition(-61006); notifyErrorMessage(getHumanLabel(), QString("Number of cells does not match number of tuples in the Attribute Matrix"), getErrorCondition()); return getErrorCondition(); } this->readDataTypeSection(in, ncells, "point_data"); } else if ( word.startsWith("POINT_DATA") ) { DataContainer::Pointer m = getDataContainerArray()->getDataContainer(getVertexDataContainerName()); m_CurrentAttrMat = m->getAttributeMatrix(getVertexAttributeMatrixName()); npts = tokens[1].toInt(&ok); if (m_CurrentAttrMat->getNumTuples() != npts) { setErrorCondition(-61007); notifyErrorMessage(getHumanLabel(), QString("Number of points does not match number of tuples in the Attribute Matrix"), getErrorCondition()); return getErrorCondition(); } this->readDataTypeSection(in, numPts, "cell_data"); } // Close the file since we are done with it. in.close(); return err; }
bool QTarDecode::decodeData(const std::vector<char> &data) { setErrorString("Unknown error"); if(data.size()<1024) return false; unsigned int offset=0; while(offset<data.size()) { //load the file name from ascii, from 0+offset with size of 100 std::string fileName(data.data()+offset,100); while(!fileName.empty() && fileName.at(fileName.size()-1)==0x00) fileName.resize(fileName.size()-1); //load the file type std::string fileType(data.data()+156+offset,1); while(!fileName.empty() && fileType.at(fileType.size()-1)==0x00) fileType.resize(fileType.size()-1); //load the ustar string std::string ustar(data.data()+257+offset,5); while(!fileName.empty() && ustar.at(ustar.size()-1)==0x00) ustar.resize(ustar.size()-1); //load the ustar version std::string ustarVersion(data.data()+263+offset,2); while(!fileName.empty() && ustarVersion.at(ustarVersion.size()-1)==0x00) ustarVersion.resize(ustarVersion.size()-1); bool ok=false; //load the file size from ascii, from 124+offset with size of 12 uint64_t finalSize=0; std::string sizeString(data.data()+124+offset,12); if(sizeString.at(sizeString.size()-1)==0x00) { //the size is in octal base sizeString.resize(sizeString.size()-1); finalSize=octaltouint64(sizeString,&ok); } else finalSize=stringtouint64(sizeString,&ok); //if the size conversion to qulonglong have failed, then qui with error if(ok==false) { //it's the end of the archive, no more verification break; } //if check if the ustar not found if(ustar!="ustar") { setErrorString("\"ustar\" string not found at "+std::to_string(257+offset)+", content: \""+ustar+"\""); return false; } if(ustarVersion!="00") { setErrorString("ustar version string is wrong, content:\""+ustarVersion+"\""); return false; } //check if the file have the good size for load the data if((offset+512+finalSize)>data.size()) { setErrorString("The tar file seem be too short"); return false; } if(fileType=="0") //this code manage only the file, then only the file is returned { std::vector<char> newdata; newdata.resize(finalSize); memcpy(newdata.data(),data.data()+512+offset,finalSize); fileList.push_back(fileName); dataList.push_back(newdata); } //calculate the offset for the next header bool retenu=((finalSize%512)!=0); //go to the next header offset+=512+(finalSize/512+retenu)*512; } if(fileList.size()>0) { std::string baseDirToTest=fileList.at(0); std::size_t found = baseDirToTest.find_last_of("/"); if(found!=std::string::npos && found>=baseDirToTest.size()) baseDirToTest.resize(baseDirToTest.size()-(baseDirToTest.size()-found)); bool isFoundForAllEntries=true; for (unsigned int i = 0; i < fileList.size(); ++i) if(!stringStartWith(fileList.at(i),baseDirToTest)) isFoundForAllEntries=false; if(isFoundForAllEntries) for (unsigned int i = 0; i < fileList.size(); ++i) fileList[i].erase(0,baseDirToTest.size()); } return true; }
bool ZFileType::isNeutubeOpenable(const std::string &filePath) { return isNeutubeOpenable(fileType(filePath)); }
bool ZFileType::isImageFile(const std::string &filePath) { return isImageFile(fileType(filePath)); }
static bool check_bytes(const ut8 *buf, ut64 length) { if (buf && length >= 0x20) { return fileType (buf + NRO_OFF (magic)) != NULL; } return false; }
bool PCBMODEL::getModelLabel( const std::string aFileName, TDF_Label& aLabel ) { MODEL_MAP::const_iterator mm = m_models.find( aFileName ); if( mm != m_models.end() ) { aLabel = mm->second; return true; } aLabel.Nullify(); Handle( TDocStd_Document ) doc; m_app->NewDocument( "MDTV-XCAF", doc ); FormatType modelFmt = fileType( aFileName.c_str() ); switch( modelFmt ) { case FMT_IGES: if( !readIGES( doc, aFileName.c_str() ) ) { std::ostringstream ostr; ostr << __FILE__ << ": " << __FUNCTION__ << ": " << __LINE__ << "\n"; ostr << " * readIGES() failed on filename '" << aFileName << "'\n"; wxLogMessage( "%s\n", ostr.str().c_str() ); return false; } break; case FMT_STEP: if( !readSTEP( doc, aFileName.c_str() ) ) { std::ostringstream ostr; ostr << __FILE__ << ": " << __FUNCTION__ << ": " << __LINE__ << "\n"; ostr << " * readSTEP() failed on filename '" << aFileName << "'\n"; wxLogMessage( "%s\n", ostr.str().c_str() ); return false; } break; // TODO: implement IDF and EMN converters default: return false; } aLabel = transferModel( doc, m_doc ); if( aLabel.IsNull() ) { std::ostringstream ostr; ostr << __FILE__ << ": " << __FUNCTION__ << ": " << __LINE__ << "\n"; ostr << " * could not transfer model data from file '" << aFileName << "'\n"; wxLogMessage( "%s\n", ostr.str().c_str() ); return false; } // attach the PART NAME ( base filename: note that in principle // different models may have the same base filename ) wxFileName afile( aFileName.c_str() ); std::string pname( afile.GetName().ToUTF8() ); TCollection_ExtendedString partname( pname.c_str() ); TDataStd_Name::Set( aLabel, partname ); m_models.insert( MODEL_DATUM( aFileName, aLabel ) ); ++m_components; return true; }
int doFuncInp(char *fromName, char *toName, char *baseSrcName, char *baseToName, int allowAppend, char *archiveExtension) { FILE *fp; char *fileBuf; char *toBuf; int ch; char *chP; struct stat st; int count=0; FileType type; int toLen; int toNameLen = strlen(toName); int archExtLen = strlen(archiveExtension); //printf("%s %s %s %s\n",fromName,toName,baseSrcName,baseToName); stat(fromName,&st); if (st.st_mode & S_IFDIR) { if (!fileExists(toName)) { if (mkdir(toName,st.st_mode)) { fprintf(stderr,"Error: Failed making directory %s\n",toName); exit(1); } } else if (!isDirectory(toName)) { fprintf(stderr,"Error: %s is not a directory, but should be\n",toName); exit(1); } } else { if (fileExists(toName)) { fprintf(stderr,"Error: File %s already exists and I'm not going to overwrite it!",toName); exit(1); } if ((fileBuf = calloc(st.st_size+1,sizeof(char))) == NULL) { fprintf(stderr,"Error: Failed allocating space for file buffer of size %ld\n", st.st_size+1); exit(1); } /* Hack */ if ((toBuf = calloc(st.st_size+1000000,sizeof(char))) == NULL) { fprintf(stderr,"Error: Failed allocating space for file buffer\n"); exit(1); } if ((fp = fopen(fromName,"r")) == NULL) { fprintf(stderr,"Error: Failed opening from perl file %s\n",fromName); exit(1); } fread(fileBuf,st.st_size,1,fp); /* chP = fileBuf; while ((ch = getc(fp)) != EOF) { count++; *chP = ch; chP++; } */ fclose(fp); if ((fp = fopen(toName,"w")) == NULL) { fprintf(stderr,"Error: Failed opening to perl file %s\n",toName); exit(1); } type = fileType(fileBuf,st.st_size); //printf("Type = %d (%s)\n",type,typeStrings[type]); copyAndReplace(fileBuf,toBuf,baseSrcName,baseToName,toName,st.st_size,&toLen,type); fwrite(toBuf,toLen,1,fp); fclose(fp); chmod(toName,st.st_mode); if (archExtLen && toNameLen > archExtLen) { //printf("toNameLen = %d archExtLen = %d toName bit = %s\n", // toNameLen,archExtLen,&(toName[toNameLen-archExtLen])); if (!strcmp(&(toName[toNameLen-archExtLen]),archiveExtension)) { char comStr[MAXPATHLEN + 1024]; sprintf(comStr,"ranlib %s",toName); printf("%s\n",comStr); system(comStr); } } free(fileBuf); free(toBuf); } return 1; }
// ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- int VTKFileReader::readHeader() { int err = 0; if (getInputFile().isEmpty() == true) { setErrorCondition(-1); notifyErrorMessage(getHumanLabel(), "FileName was not set and must be valid", -1); return -1; } if (NULL == getDataContainerArray()->getDataContainer(getDataContainerName()).get()) { setErrorCondition(-1); notifyErrorMessage(getHumanLabel(), "DataContainer Pointer was NULL and must be valid", -1); return -1; } QFile in(getInputFile()); if (!in.open(QIODevice::ReadOnly | QIODevice::Text)) { QString msg = QObject::tr("VTF file could not be opened: %1").arg(getInputFile()); setErrorCondition(-100); notifyErrorMessage(getHumanLabel(), msg, getErrorCondition()); return -100; } QByteArray buf; buf = in.readLine(); // Read Line 1 - VTK Version Info buf = in.readLine(); // Read Line 2 - User Comment setComment(QString(buf.trimmed())); buf = in.readLine(); // Read Line 3 - BINARY or ASCII QString fileType(buf); if (fileType.startsWith("BINARY") == true) { setFileIsBinary(true); } else if (fileType.startsWith("ASCII") == true) { setFileIsBinary(false); } else { err = -1; qDebug() << "The file type of the VTK legacy file could not be determined. It should be ASCII' or 'BINARY' and should appear on line 3 of the file." ; return err; } QList<QByteArray> tokens; buf = in.readLine(); // Read Line 4 - Type of Dataset { tokens = buf.split(' '); setDatasetType(QString(tokens[1])); } buf = in.readLine(); // Read Line 5 which is the Dimension values bool ok = false; int64_t dims[3]; tokens = buf.split(' '); dims[0] = tokens[1].toLongLong(&ok, 10); dims[1] = tokens[2].toLongLong(&ok, 10); dims[2] = tokens[3].toLongLong(&ok, 10); #if (CMP_SIZEOF_SSIZE_T==4) int64_t max = std::numeric_limits<size_t>::max(); #else int64_t max = std::numeric_limits<int64_t>::max(); #endif if (dims[0] * dims[1] * dims[2] > max ) { err = -1; QString ss = QObject::tr("The total number of elements '%1' is greater than this program can hold. Try the 64 bit version.").arg(dims[0] * dims[1] * dims[2]); setErrorCondition(err); notifyErrorMessage(getHumanLabel(), ss, getErrorCondition()); return err; } if (dims[0] > max || dims[1] > max || dims[2] > max) { err = -1; QString ss = QObject::tr("One of the dimensions is greater than the max index for this sysem. Try the 64 bit version. dim[0]=%1 dim[1]=%2im[2]=%3")\ .arg(dims[0]).arg(dims[1]).arg(dims[2]); setErrorCondition(err); notifyErrorMessage(getHumanLabel(), ss, getErrorCondition()); return err; } size_t dcDims[3] = { static_cast<size_t>(dims[0]), static_cast<size_t>(dims[1]), static_cast<size_t>(dims[2]) }; DataContainer::Pointer dc = getDataContainerArray()->getDataContainer(getDataContainerName()); if (dc.get() == NULL) { return -1; } ImageGeom::Pointer image = dc->getGeometryAs<ImageGeom>(); if (image.get() == NULL) { return -1; } image->setDimensions(dcDims); buf = in.readLine(); // Read Line 6 which is the Origin values float origin[3]; tokens = buf.split(' '); origin[0] = tokens[1].toFloat(&ok); origin[1] = tokens[2].toFloat(&ok); origin[2] = tokens[3].toFloat(&ok); image->setOrigin(origin); buf = in.readLine(); // Read Line 7 which is the Scaling values float resolution[3]; tokens = buf.split(' '); resolution[0] = tokens[1].toFloat(&ok); resolution[1] = tokens[2].toFloat(&ok); resolution[2] = tokens[3].toFloat(&ok); image->setResolution(resolution); return err; }
bool PCBMODEL::getModelLabel( const std::string aFileName, TDF_Label& aLabel ) { MODEL_MAP::const_iterator mm = m_models.find( aFileName ); if( mm != m_models.end() ) { aLabel = mm->second; return true; } aLabel.Nullify(); Handle( TDocStd_Document ) doc; m_app->NewDocument( "MDTV-XCAF", doc ); FormatType modelFmt = fileType( aFileName.c_str() ); switch( modelFmt ) { case FMT_IGES: if( !readIGES( doc, aFileName.c_str() ) ) { std::ostringstream ostr; #ifdef __WXDEBUG__ ostr << __FILE__ << ": " << __FUNCTION__ << ": " << __LINE__ << "\n"; #endif /* __WXDEBUG */ ostr << " * readIGES() failed on filename '" << aFileName << "'\n"; wxLogMessage( "%s", ostr.str().c_str() ); return false; } break; case FMT_STEP: if( !readSTEP( doc, aFileName.c_str() ) ) { std::ostringstream ostr; #ifdef __WXDEBUG__ ostr << __FILE__ << ": " << __FUNCTION__ << ": " << __LINE__ << "\n"; #endif /* __WXDEBUG */ ostr << " * readSTEP() failed on filename '" << aFileName << "'\n"; wxLogMessage( "%s", ostr.str().c_str() ); return false; } break; case FMT_WRL: /* WRL files are preferred for internal rendering, * due to superior material properties, etc. * However they are not suitable for MCAD export. * * If a .wrl file is specified, attempt to locate * a replacement file for it. * * If a valid replacement file is found, the label * for THAT file will be associated with the .wrl file * */ { wxFileName wrlName( aFileName ); wxString basePath = wrlName.GetPath(); wxString baseName = wrlName.GetName(); // List of alternate files to look for // Given in order of preference // (Break if match is found) wxArrayString alts; // Step files alts.Add( "stp" ); alts.Add( "step" ); alts.Add( "STP" ); alts.Add( "STEP" ); alts.Add( "Stp" ); alts.Add( "Step" ); // IGES files alts.Add( "iges" ); alts.Add( "IGES" ); alts.Add( "igs" ); alts.Add( "IGS" ); //TODO - Other alternative formats? for( auto alt : alts ) { wxFileName altFile( basePath, baseName + "." + alt ); if( altFile.IsOk() && altFile.FileExists() ) { std::string altFileName = altFile.GetFullPath().ToStdString(); if( getModelLabel( altFileName, aLabel ) ) { return true; } } } } break; // TODO: implement IDF and EMN converters default: return false; } aLabel = transferModel( doc, m_doc ); if( aLabel.IsNull() ) { std::ostringstream ostr; #ifdef __WXDEBUG__ ostr << __FILE__ << ": " << __FUNCTION__ << ": " << __LINE__ << "\n"; #endif /* __WXDEBUG */ ostr << " * could not transfer model data from file '" << aFileName << "'\n"; wxLogMessage( "%s", ostr.str().c_str() ); return false; } // attach the PART NAME ( base filename: note that in principle // different models may have the same base filename ) wxFileName afile( aFileName.c_str() ); std::string pname( afile.GetName().ToUTF8() ); TCollection_ExtendedString partname( pname.c_str() ); TDataStd_Name::Set( aLabel, partname ); m_models.insert( MODEL_DATUM( aFileName, aLabel ) ); ++m_components; return true; }
bool ZFileType::isObjectFile(const std::string &filePath) { return isObjectFile(fileType(filePath)); }