void cv::glob(String pattern, std::vector<String>& result, bool recursive) { result.clear(); String path, wildchart; if (isDir(pattern, 0)) { if(strchr(dir_separators, pattern[pattern.size() - 1]) != 0) { path = pattern.substr(0, pattern.size() - 1); } else { path = pattern; } } else { size_t pos = pattern.find_last_of(dir_separators); if (pos == String::npos) { wildchart = pattern; path = "."; } else { path = pattern.substr(0, pos); wildchart = pattern.substr(pos + 1); } } glob_rec(path, wildchart, result, recursive); std::sort(result.begin(), result.end()); }
std::vector<File> File::ls(File::NodeType filter, bool include_hidden) const { if(!(exists() && isDir())) return std::vector<File>(0); std::vector<std::string> files; Poco::File(fullPath()).list(files); std::list<File> nodes; for(auto it = files.begin(); it != files.end(); ++it) { File file = subfile(*it); NodeType nodeType = file.nodeType(); if(nodeType & filter) { if(!include_hidden && (nodeType & HIDDEN)) continue; nodes.push_back(file); } } std::vector<File> vecnodes; for(auto it = nodes.begin(); it != nodes.end(); ++it) vecnodes.push_back(*it); return vecnodes; }
/* * Begin code I did not write. * This code is partly derived from http://stackoverflow.com/questions/4989431/how-to-use-s-isreg-and-s-isdir-posix-macros * If the source code requires you to include copyright, put copyright here. */ void ProcessFilenameFailure(char * filename) { if(strlen(filename)!=0) { if(filename[0]=='-') { fprintf(stderr,"(malformed command)\n"); exit(-1); } } if( access( filename, F_OK ) != -1 ) { #ifdef DEBUG2 fprintf(stdout,"file exist\n"); #endif } else { fprintf(stderr,"input file/path %s does not exist\n",filename); exit(-1); } if( access( filename, R_OK ) != -1 ) { #ifdef DEBUG2 fprintf(stdout,"file has Read permissions\n"); #endif } else { fprintf(stderr,"input file/path %s cannot be opened - access denied\n",filename); exit(-1); } if(isDir(filename)) { fprintf(stderr,"(input file: %s is a directory)\n",filename); exit(-1); } }
/** Create the given directory (create all intermediate directories if needed) */ int mkdirs(const std::string &path) { if (path.empty()) return -1; int i = 0; size_t offset = 0; size_t pos = 0; while (pos != std::string::npos) { pos = path.find_first_of("/", offset); std::string subpath; if (pos == std::string::npos) { subpath = path; } else { subpath = path.substr(0, pos); offset = pos+1; } if (!isDir(subpath)) { int r = mkdir(subpath.c_str(), 0777); if (r != 0) return -1; } } return 0; }
// changes the working directory void cwd(char **params, short *abor, int fd, struct state *cstate, struct config *configuration) { if (!cstate->logged) { respond(fd, 5, 3, 0, "Not logged in."); return; } if (params[0] == NULL) { respond(fd, 5, 0, 4, "Need directory name."); return; } char old_path[PATH_LENGTH]; char dir[PATH_LENGTH]; strncpy(old_path, cstate->path, PATH_LENGTH - 1); old_path[PATH_LENGTH - 1] = '\0'; // loads the full path to the given directory into dir variable if (getFullPath(dir, cstate, configuration, params[0]) == -1) { respond(fd, 4, 5, 1, "Internal server error."); return; } // checks the directory existence if (isDir(dir) == -1) { respond(fd, 4, 5, 1, "Directory does not exist."); return; } // changes the "chrooted" part of path if (changeDir(cstate->path, params[0]) == NULL) { strcpy(cstate->path, old_path); respond(fd, 4, 5, 1, "Internal server error."); return; } respond(fd, 2, 5, 7, cstate->path); }
//- write field void dsmcVibrationalDegreesOfFreedomZone::writeField() { const Time& runTime = time_.time(); if(runTime.outputTime()) { fileName timePath(runTime.path()/runTime.timeName()/"uniform"); if (!isDir(timePath)) { mkDir(timePath); } const scalarField& timeField = time_.averagingTimes(); writeTimeData(timePath, fieldName_+"_"+regionName_+"_vibrationalDegreesOfFreedom", timeField, vDoFField_); //- reset if(time_.resetFieldsAtOutput()) { vibrationalETotal_ = scalar(0.0); nParcels_ = scalar(0.0); vibT_ = scalar(0.0); vDof_ = scalar(0.0); vibTxvDof_ = scalar(0.0); } } }
void OSInterface::doMove(std::string &src, std::string &dst){ std::stringstream ss; if(isDir(src)){ OSInterface os; os.getDirInfo(src, "*"); if(mkdir(dst.c_str(), 0755) == -1) throw new OSException(src, strerror(errno)); for(auto &a : os.dirs){ std::string nsrc, ndst; nsrc = src; nsrc.push_back(dir_sep); nsrc.append(a->name); ndst = dst; ndst.push_back(dir_sep); ndst.append(a->name); doMove(nsrc, ndst); } if(rmdir(src.c_str()) == -1) throw new OSException(src, strerror(errno)); }else{ ss << "Move " << src << " to: " << dst << std::endl; if(((link(src.c_str(), dst.c_str())) == -1) || (unlink(src.c_str()) == -1)) throw new OSException(ss.str(), strerror(errno)); } }
void Path::visit(const std::function<VisitResult(const Path &path)> &callback) const { if (!callback || !isDir()) return; Set<Path> seenDirs; visitorWrapper(*this, callback, seenDirs); }
std::string CommandEventHandler::cd(std::vector<std::string>& args) { std::string path(args.size() ? args[0] : ""); if (path.compare("") == 0) path = "/"; const char *p = path.c_str(); // check if path exists and it is a dir std::string ret = isDir(path); if (ret.compare("TRUE") != 0) { if (ret.compare("FALSE") == 0) return agentWarn("path is not a dir"); return ret; } // check for read permissions PRStatus success = PR_Access(p, PR_ACCESS_READ_OK); if (success == PR_SUCCESS) { // update the cwd int s = chdir(p); if (s == 0) return ""; } return agentWarn("no permissions"); }
void AVLDeletionFileInput(char *filename,char deletionstrArr[][MAXBUFSIZE],int numofdelstr) { #ifdef DEBUG1 fprintf(stdout,"AVLDeletionFileInput::filename:%s\n",filename); fprintf(stdout,"AVLDeletionFileInput::Deletion strings are :\n"); for(int i=0; i<numofdelstr;i++) { fprintf(stdout,"%s\n",deletionstrArr[i]); } #endif ifstream in; ProcessFilenameFailure(filename); in.open(filename); if (in.fail()) { fprintf(stderr, "(Cannot open %s) \n",filename); exit(-1); } if(isDir(filename)) { fprintf(stderr,"(input file: %s is a directory)\n",filename); exit(-1); } //My570BST *BST = ProcessAVLDeletion(in); //BUILD BST-AVL TREE First in.close(); /* Commented--- since we havent yet implemented node deletion for AVL tree.. for(int i =0;i<numofdelstr;i++) { (void)BST->DeleteNode((void*)deletionstrArr[i]); fprintf(stdout,"Deleted \"%s\":\n\n",deletionstrArr[i]); BST->DisplayTree(); if(i!=numofdelstr-1) fprintf(stdout,"\n"); } */ }
/* * This slot uses for setting root index in a current view only if a dir was activated. * If there are trying to activate a file, nothing will be done. */ void MainWindow::slotActivatedOnlyDirs(const QModelIndex &index) { QAbstractItemView *view = 0; if (isDir(index) && (view = dynamic_cast<QAbstractItemView *>(sender()) ) ) view->setRootIndex(index); resetRightView(index); }
void printInode(INODE * inodeP) { if(inodeP == NULL){ return; } if(isDir(inodeP)){ printf("d"); } else{ printf("-"); } printAuthority(inodeP); printf("\t"); struct tm * tmpTime ; //printf(ctime(&inodeP->cTime)); //printf(ctime(&inodeP->aTime)); //printf(ctime(&inodeP->mTime)); tmpTime = localtime(&inodeP->cTime); printf("cTime:%02d-%02d\t", tmpTime->tm_min, tmpTime->tm_sec); tmpTime = localtime(&inodeP->aTime); printf("aTime:%02d-%02d\t", tmpTime->tm_min, tmpTime->tm_sec); //tmpTime = localtime(&inodeP->mTime); //printf("修改时间:%d-%d-%d\t", tmpTime->tm_year, tmpTime->tm_mon, tmpTime->tm_mday); printf("size:%d B\t", inodeP->length); }
AbstractFSProvider::status_t ZIPProvider::makeDirRecursive(const FileName & url) { if(isDir(url)) { return AbstractFSProvider::OK; } std::string archiveFileName; FileName file; decomposeURL(url, archiveFileName, file); const std::string path = file.getPath(); // Split path into directory components size_t pos = 0; while(pos != path.size()) { pos = path.find('/', pos); if(pos == std::string::npos) { break; } const std::string subPath = path.substr(0, pos + 1); ++pos; if(makeDir(FileName(archiveFileName + '$' + subPath)) != AbstractFSProvider::OK) { return AbstractFSProvider::FAILURE; } } return AbstractFSProvider::OK; }
int setupPath(char * path){ // This file creates a directory for every instance of '/' in path (if doesn't exist) char currentPath[PATH_MAX]; int currentCharIndex = 0; while((currentPath[currentCharIndex] = path[currentCharIndex]) != '\0'){ if(currentPath[currentCharIndex] == '/'){ currentPath[currentCharIndex + 1] = '\0'; if(mkdir(currentPath, S_IXUSR | S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IXGRP | S_IROTH | S_IXOTH) != 0){ // Directory already exists, but that's okay so reset errno errno = 0; } // Verify directory has been made switch (isDir(currentPath)){ case -1: return -1; break; case 0: snprintf(errDesc, ERR_STATUS_LENGTH, "validating %s is a directory", currentPath); return -1; break; } } currentCharIndex++; } return 0; }
void SettingsDialog::accept() { auto autoSave = QFileInfo(ui->autoSaveDirectory->text()); if (!autoSave.exists()) { QDir().mkpath(autoSave.absoluteFilePath()); } if (!autoSave.exists() || !autoSave.isDir() || !autoSave.isWritable()) { QMessageBox msg(this); msg.setIcon(QMessageBox::Warning); msg.setText("Can not access auto save directory"); msg.setInformativeText(QString("Can not access auto save directory %1").arg(autoSave.absoluteFilePath())); msg.exec(); return; } QSettings settings; settings.setValue("colorBackground", ui->background->currentIndex()); settings.setValue("breakLines", ui->breakLines->isChecked()); settings.setValue("maxMessages", ui->maxMessages->value()); settings.setValue("autoSaveDirectory", ui->autoSaveDirectory->text()); settings.setValue("timestampPrecision", ui->timestampFormat->currentIndex()); QDialog::accept(); }
std::string CommandEventHandler::isDir(std::vector<std::string>& args) { if (args.size() < 1) return agentWarnInvalidNumArgs(1); return isDir(args[0]); }
void KDirListBox::keyPressEvent( QKeyEvent *e ) { int index = 0; switch ( e->key() ) { case Key_Return: // fall through case Key_Enter: index = currentItem(); if ( index == -1 ) return; if ( isDir( index ) ) select( index ); break; case Key_Home: highlightItem( 0 ); setTopCell( 0 ); // somehow highlightItem() does NOT scroll!? break; case Key_End: index = QListBox::count() -1; if ( index >= 0 ) { highlightItem( index ); // somehow highlightItem() does NOT scroll!? setBottomItem( index ); } break; default: QListBox::keyPressEvent( e ); } }
std::string CommandEventHandler::ls(std::vector<std::string>& args) { std::string path(args.size() ? args[0] : ""); if (path.compare("") == 0) path = "."; std::ostringstream out; std::string ret = isDir(path); if (ret.compare("TRUE") != 0) { if (ret.compare("FALSE") == 0) return agentWarn("path is not a dir"); return ret; } PRDir *dir = PR_OpenDir(path.c_str()); PRDirEntry *entry = PR_ReadDir(dir, PR_SKIP_BOTH); while (entry) { out << std::string(entry->name) << ENDL; entry = PR_ReadDir(dir, PR_SKIP_BOTH); } if (PR_CloseDir(dir) != PR_SUCCESS) return agentWarn("could not close dir object"); std::string output = out.str(); if (output.size()) output.erase(output.size() - 1); // erase the extra newline return output; }
//- Constructor clockTimer::clockTimer(Time& t, word fieldName, bool write) : time_(t), fieldName_(fieldName), instTimeIndex_(0.0), timeIndex_(0.0), totalDuration_(0.0), duration_(0.0), instantDuration_(0.0), writeOut_(write), timePath_() { if(writeOut_) { // directory: case/boundaries timePath_ = time_.path()/"timings"; if(isDir(timePath_)) { rmDir(timePath_); } if(Pstream::master()) { mkDir(timePath_); } } }
void CurlTransportAgent::setSSL(const std::string &cacerts, bool verifyServer, bool verifyHost) { m_cacerts = cacerts; CURLcode code = CURLE_OK; if (!m_cacerts.empty()) { if (isDir(m_cacerts)) { // libcurl + OpenSSL does not work with a directory set in CURLOPT_CAINFO. // Must set the directory name as CURLOPT_CAPATH. // // Hopefully libcurl NSS also finds the directory name // here ("NSS-powered libcurl provides the option only for // backward compatibility. "). code = curl_easy_setopt(m_easyHandle, CURLOPT_CAPATH, m_cacerts.c_str()); } else { code = curl_easy_setopt(m_easyHandle, CURLOPT_CAINFO, m_cacerts.c_str()); } } if (!code) { code = curl_easy_setopt(m_easyHandle, CURLOPT_SSL_VERIFYPEER, (long)verifyServer); } if (!code) { code = curl_easy_setopt(m_easyHandle, CURLOPT_SSL_VERIFYHOST, (long)(verifyHost ? 2 : 0)); } checkCurl(code); }
void OSInterface::doRemove(std::string &src){ std::wstring oldf; std::stringstream ss; oldf.assign(src.begin(), src.end()); ss << "Remove " << src << std::endl; if(isDir(src)){ std::string warn = src + "\n is a directory. Remove anyvway? \n"; if(QMessageBox::question(nullptr, "Remove directory", QString::fromStdString(warn), QMessageBox::Yes|QMessageBox::Default, QMessageBox::No|QMessageBox::Escape) == QMessageBox::No) throw std::exception(); OSInterface os; os.getDirInfo(src, "*"); for(auto &a : os.dirs){ std::string nsrc; nsrc = src; nsrc.push_back(dir_sep); nsrc.append(a->name); doRemove(nsrc); } if(!RemoveDirectory(oldf.c_str())) throw new OSException(ss.str(), strerror(errno)); }else{ if(!DeleteFile(oldf.c_str())) throw new OSException(ss.str(), strerror(errno)); } }
void Foam::proxySurfaceWriter<Type>::write ( const fileName& outputDir, const fileName& surfaceName, const pointField& points, const faceList& faces, const bool verbose ) const { // avoid bad values if (ext_.empty()) { return; } if (!isDir(outputDir)) { mkDir(outputDir); } fileName fName(outputDir/surfaceName + "." + ext_); if (verbose) { Info<< "Writing geometry to " << fName << endl; } MeshedSurfaceProxy<face> ( points, faces ).write(fName); }
QMimeType KFileItem::determineMimeType() const { if (!d) { return QMimeType(); } if (!d->m_mimeType.isValid() || !d->m_bMimeTypeKnown) { QMimeDatabase db; if (isDir()) { d->m_mimeType = db.mimeTypeForName(QStringLiteral("inode/directory")); } else { bool isLocalUrl; const QUrl url = mostLocalUrl(&isLocalUrl); d->m_mimeType = db.mimeTypeForUrl(url); // was: d->m_mimeType = KMimeType::findByUrl( url, d->m_fileMode, isLocalUrl ); // => we are no longer using d->m_fileMode for remote URLs. Q_ASSERT(d->m_mimeType.isValid()); //qDebug() << d << "finding final mimetype for" << url << ":" << d->m_mimeType.name(); } d->m_bMimeTypeKnown = true; } if (d->m_delayedMimeTypes) { // if we delayed getting the iconName up till now, this is the right point in time to do so d->m_delayedMimeTypes = false; d->m_useIconNameCache = false; (void)iconName(); } return d->m_mimeType; }
void removeFile(const char *filename) { bool isdir; isDir(filename,isdir); if (isdir) { #ifdef _WIN32 // no rmdir? if (RemoveDirectory(filename)==0) return; DWORD err = GetLastError(); if ( (err==ERROR_FILE_NOT_FOUND) || (err==ERROR_PATH_NOT_FOUND) ) return; throwError((int)err,"removeFile"); // shouldn't really pass win error here #else if (rmdir(filename) == 0) return; #endif } else { if (_unlink(filename) == 0) return; } if (ENOENT!=errno) throwError(errno,"removeFile"); }
Path& Path::operator+=(const Path &rhs) { if (isDir() && !rhs.isAbsolute()) { mPaths.insert(mPaths.end(), rhs.mPaths.begin(), rhs.mPaths.end()); mFullName = fullname(DIR_SEP); } return *this; }
void outSize(char* dName){ struct stat statbuf; stat(dName, &statbuf); DIR *dir_ptr; struct dirent *direntp; if(isDir(dName)) { printf ("%s is a directory.\n", dName); printf ("%s has %ld bytes.\n", dName, statbuf.st_size); if((dir_ptr = opendir( dName)) == NULL) fprintf(stderr, "Can not open %s\n", dName); else { while((direntp = readdir( dir_ptr)) != NULL && strcmp(dName, ".") != 0 && strcmp(dName, "..") != 0) outSize(direntp->d_name); closedir(dir_ptr); } } else { printf ("%s is a regular file.\n", dName); printf ("%s has %ld bytes.\n", dName, statbuf.st_size); } }
int storage_load_paths_from_conf_file(IniContext *pItemContext) { char *pPath; int result; pPath = iniGetStrValue(NULL, "base_path", pItemContext); if (pPath == NULL) { logError("file: "__FILE__", line: %d, " \ "conf file must have item \"base_path\"!", __LINE__); return ENOENT; } snprintf(g_fdfs_base_path, sizeof(g_fdfs_base_path), "%s", pPath); chopPath(g_fdfs_base_path); if (!fileExists(g_fdfs_base_path)) { logError("file: "__FILE__", line: %d, " \ "\"%s\" can't be accessed, error info: %s", \ __LINE__, STRERROR(errno), g_fdfs_base_path); return errno != 0 ? errno : ENOENT; } if (!isDir(g_fdfs_base_path)) { logError("file: "__FILE__", line: %d, " \ "\"%s\" is not a directory!", \ __LINE__, g_fdfs_base_path); return ENOTDIR; } g_fdfs_store_paths.paths = storage_load_paths_from_conf_file_ex( \ pItemContext, NULL, true, &g_fdfs_store_paths.count, &result); return result; }
void Path::visit(VisitCallback callback, void *userData) const { if (!callback || !isDir()) return; Set<Path> seenDirs; visitorWrapper(*this, callback, seenDirs, userData); }
std::vector<std::string> listFiles(const std::string& directory, bool recursive) { // create a vector to store the files std::vector<std::string> files; // create a vector to store the directories std::stack<std::string> directories; // adds the specified directory to the vector directories.push(directory); // loop through all the directories using a depth-first search while (!directories.empty()) { // retrieve the last directory in the vector, beginning with the initial directory auto directory = directories.top(); // immediately remove the directory that was found directories.pop(); // loop through every file within the directory for (auto&& file : listDir(directory)) { // specify the correct path within the directory auto path = directory + "/" + file; // check if the given path is a directory if (isDir(path)) { // check if the function is recursive if (recursive) { // append the path to the directories vector directories.push(path); } } else { // append the path to the paths vector files.push_back(path); } } } // return the list of files return files; }
int accessDir(const char *path) { DIR *dirp; struct dirent *dir; char fname[1024]; if((dirp = opendir(path)) == NULL) { perror("Open dir failed"); return -1; } while((dir = readdir(dirp))) { if(strcmp(dir->d_name, ".") == 0|| strcmp(dir->d_name, "..") == 0) { continue; } sprintf(fname, "%s/%s", path, dir->d_name); if(isDir(fname)) { printf("dirctory %s\n", dir->d_name); accessDir(fname); } else printf("file %s\n", dir->d_name); } closedir(dirp); return 1; }