//============================================================================== bool File::setReadOnly (const bool shouldBeReadOnly, const bool applyRecursively) const { bool worked = true; if (applyRecursively && isDirectory()) { Array <File> subFiles; findChildFiles (subFiles, File::findFilesAndDirectories, false); for (int i = subFiles.size(); --i >= 0;) worked = subFiles.getReference(i).setReadOnly (shouldBeReadOnly, true) && worked; } return setFileReadOnlyInternal (shouldBeReadOnly) && worked; }
QString URLUtil::extractPathNameAbsolute( const KURL &url ) { if (isDirectory( url )) return url.path( +1 ); // with trailing "/" if none is present else { // Ok, this is an over-tight pre-condition on "url" since I hope nobody will never // stress this function with absurd cases ... but who knows? /* QString path = url.path(); QFileInfo fi( path ); // Argh: QFileInfo is back ;)) return ( fi.exists()? path : QString() ); */ return url.path(); } }
bool os_link_symbolic(const std::string &target, const std::string &lname, void* transaction, bool* isdir) { bool l_isdir; if(isdir!=NULL) { l_isdir=*isdir; } else { l_isdir=isDirectory(target, NULL); } if(!l_isdir || !os_path_absolute(target) ||!os_link_symbolic_junctions(target, lname, transaction) ) return os_link_symbolic_symlink(target, lname, transaction, isdir); return true; }
std::string FileUtils::getFileNameWithoutExtension(const std::string& filePath)const { std::string fileName = ""; if (!isDirectory(filePath)) { size_t posStart = filePath.find_last_of("/"); size_t posEnd = filePath.find_last_of("."); if (posEnd == std::string::npos) posEnd = filePath.size() - 1; if (posStart != std::string::npos) { fileName = filePath.substr(posStart + 1, posEnd - posStart-1); } } return fileName; }
static int asepsis_handle_rename(const char* path1, const char* path2) { int res = 0; if (isPrefixPath(path1) || isPrefixPath(path2)) { return 0; } char prefixPath1[SAFE_PREFIX_PATH_BUFFER_SIZE]; if (!makePrefixPath(path1, prefixPath1)) { return 0; // the prefixed path would be too long } char prefixPath2[SAFE_PREFIX_PATH_BUFFER_SIZE]; if (!makePrefixPath(path2, prefixPath2)) { return 0; // the prefixed path would be too long } SUSPEND_LOCK_CHECK(); if (!isDirectory(prefixPath1)) { // nothing to do, source dir is not present in our cache SUSPEND_LOCK_RELEASE(); return 0; } // do mirror rename DLOG("handle rename %s -> %s", prefixPath1, prefixPath2); SERIALIZATION_LOCK_CHECK(); // here we need to be especially careful // rename(2) may fail under some special circumstances // 1. something gets into the way of renaming // 2. parent folder is missing for new name rmdir_recursive(prefixPath2); // there may be some old content (pathological case) ensureDirectoryForPath(prefixPath2); // like mkdir -p $prefixPath2 (but excluding last directory) // ok, now it should be safe to call rename res = rename(prefixPath1, prefixPath2); // this is dangerous, but we know that our path has prefix at least if (res) { ERROR("unable to rename directories %s -> %s (%s)", prefixPath1, prefixPath2, strerror(errno)); } SERIALIZATION_LOCK_RELEASE(); SUSPEND_LOCK_RELEASE(); return res; }
//Assumes normalisedDirectoryName ends with the directory name, e.g. "c:\foo" NOT "c:\foo\" bool listFiles(const char *normalisedDirectoryName, std::vector<FileEntry *> *&files) { if (!isDirectory(normalisedDirectoryName)) { return false; } files = new std::vector<FileEntry *>(); DIR *dir; struct dirent *dirp; dir = opendir(normalisedDirectoryName); if (dir == NULL) { return false; } while ((dirp = readdir(dir)) != NULL) { pushFile(files, dirp); } closedir(dir); return true; }
bool createDirectory (string const& name, int mask, int* errorNumber) { if (errorNumber != 0) { *errorNumber = 0; } int result = TRI_MKDIR(name.c_str(), mask); if (result != 0 && errno == EEXIST && isDirectory(name)) { result = 0; } if (errorNumber) { *errorNumber = errno; } return (result != 0) ? false : true; }
bool INotifyEventPublisher::isPathMonitored(const std::string& path) const { WriteLock lock(mutex_); std::string parent_path; if (!isDirectory(path).ok()) { if (path_descriptors_.find(path) != path_descriptors_.end()) { // Path is a file, and is directly monitored. return true; } // Important to add a trailing "/" for inotify. parent_path = fs::path(path).parent_path().string() + '/'; } else { parent_path = path; } // Directory or parent of file monitoring auto path_iterator = path_descriptors_.find(parent_path); return (path_iterator != path_descriptors_.end()); }
void Initializer::initDaemon() const { if (FLAGS_config_check) { // No need to daemonize, emit log lines, or create process mutexes. return; } #ifndef __APPLE__ // OS X uses launchd to daemonize. if (osquery::FLAGS_daemonize) { if (daemon(0, 0) == -1) { shutdown(EXIT_FAILURE); } } #endif // Print the version to SYSLOG. syslog( LOG_NOTICE, "%s started [version=%s]", binary_.c_str(), kVersion.c_str()); // Check if /var/osquery exists if ((Flag::isDefault("pidfile") || Flag::isDefault("database_path")) && !isDirectory(OSQUERY_HOME)) { std::cerr << CONFIG_ERROR; } // Create a process mutex around the daemon. auto pid_status = createPidFile(); if (!pid_status.ok()) { LOG(ERROR) << binary_ << " initialize failed: " << pid_status.toString(); shutdown(EXIT_FAILURE); } // Nice ourselves if using a watchdog and the level is not too permissive. if (!FLAGS_disable_watchdog && FLAGS_watchdog_level >= WATCHDOG_LEVEL_DEFAULT && FLAGS_watchdog_level != WATCHDOG_LEVEL_DEBUG) { // Set CPU scheduling I/O limits. setpriority(PRIO_PGRP, 0, 10); #ifdef __linux__ // Using: ioprio_set(IOPRIO_WHO_PGRP, 0, IOPRIO_CLASS_IDLE); syscall(SYS_ioprio_set, IOPRIO_WHO_PGRP, 0, IOPRIO_CLASS_IDLE); #elif defined(__APPLE__) setiopolicy_np(IOPOL_TYPE_DISK, IOPOL_SCOPE_PROCESS, IOPOL_THROTTLE); #endif } }
const std::string ChildrenFirstTraverse::next(Stack* itStack, bool* isFinished) { // pointer mustn't point to NULL and iteration mustn't be finished poco_check_ptr(isFinished); poco_assert(!(*isFinished)); std::stack<DirectoryIterator> it; //_depthDeterminer(it); // go deeper into not empty directory // (if depth limit allows) bool isDepthLimitReached = isFiniteDepth() && _depthDeterminer(*itStack) >= _maxDepth; if (!isDepthLimitReached && isDirectory(*itStack->top())) { DirectoryIterator child_it(itStack->top().path()); // check if directory is empty if (child_it != _itEnd) { itStack->push(child_it); return child_it->path(); } } ++(itStack->top()); poco_assert(!itStack->empty()); // return up until there isn't right sibling while (itStack->top() == _itEnd) { itStack->pop(); // detect end of traversal if (itStack->empty()) { *isFinished = true; return _itEnd->path(); } else { ++(itStack->top()); } } return itStack->top()->path(); }
void mkdir(const std::string& directoryPath) { try { if (!directoryPath.empty()) { // Create folder if it does not exist const boost::filesystem::path directory{directoryPath}; if (!isDirectory(directoryPath) && !boost::filesystem::create_directory(directory)) error("Could not write to or create directory to save processed frames.", __LINE__, __FUNCTION__, __FILE__); }; } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); } }
bool File::copyDirectoryTo (const File& newDirectory) const { if (isDirectory() && newDirectory.createDirectory()) { for (auto& f : findChildFiles (File::findFiles, false)) if (! f.copyFileTo (newDirectory.getChildFile (f.getFileName()))) return false; for (auto& f : findChildFiles (File::findDirectories, false)) if (! f.copyDirectoryTo (newDirectory.getChildFile (f.getFileName()))) return false; return true; } return false; }
void walk(std::string path, TestResults &accumulatedResults) { DIR *d = opendir(path.c_str()); struct dirent e; struct dirent *ep; while (!readdir_r(d, &e, &ep) && ep) { std::string filename = e.d_name; std::string filepath = path + "/" + filename; if (filename == "." || filename == "..") continue; if (filename == "manifest.yaml") processManifest(filepath, accumulatedResults); else if (isDirectory(filepath)) walk(filepath, accumulatedResults); } }
// This is a recursive function that goes through each file or folder, starting in "startingPath", and if it's a file, it adds it to the "fileNames" array, if it's a folder, it goes inside this folder and does the same thing void goInside(char* startingPath, char*** fileNames, char* extFilter, long* currentFile) { // Opens the current dir DIR* pDir = opendir (startingPath); struct dirent *pDirent; if (pDir == NULL) { printf ("Cannot open directory: '%s'\n", startingPath); exit(1); } // Writes all the file names in this dir, into the file while ((pDirent = readdir(pDir)) != NULL) { char* fileName = pDirent->d_name; //Makes sure it doesn't write stuff like "." or ".." into the file if((strcmpi(fileName,".") != 0) && (strcmpi(fileName,"..") != 0)) { //Creates the complete path (E.g. from C:\folder goes to c:\folder\something) char* completePath = buildFullPath(startingPath,fileName); // If it's a file, not a folder if (!isDirectory(completePath)) { // If there is no extension restriction or the file we are reading matches the extension restriction if ((strcmpi(extFilter,"*") == 0) || (strcmpi(getFileExt(fileName),extFilter) == 0)) { (*fileNames) = (char**) realloc((*fileNames),((*currentFile) + 1) * sizeof(char*)); (*fileNames)[(*currentFile)] = (char*) malloc(strlen(fileName) + 1); // Allocates the string strcpy((*fileNames)[(*currentFile)],fileName); // Copies the file name to that string (*currentFile)++; } } else { strcat(completePath,"\\"); goInside(completePath,fileNames,extFilter,currentFile); } } } //Closes the dir and the file closedir (pDir); }
bool touch(const bfs::path& path) { if (pathExists(path)) { return (utimes(path.c_str(), NULL) == 0); } if (!isDirectory(path.parent_path())) { return false; } int fd = open(path.c_str(), O_EXCL | O_CREAT | O_WRONLY, 0644); if (fd < 0) return false; close(fd); return true; }
static Array<File> getAllPossibleModulePathsFromExporters (Project& project) { StringArray paths; for (Project::ExporterIterator exporter (project); exporter.next();) { auto& modules = project.getModules(); auto n = modules.getNumModules(); for (int i = 0; i < n; ++i) { auto id = modules.getModuleID (i); if (modules.shouldUseGlobalPath (id)) continue; const auto path = exporter->getPathForModuleString (id); if (path.isNotEmpty()) paths.addIfNotAlreadyThere (path); } String oldPath (exporter->getLegacyModulePath()); if (oldPath.isNotEmpty()) paths.addIfNotAlreadyThere (oldPath); } Array<File> files; for (auto& path : paths) { auto f = project.resolveFilename (path); if (f.isDirectory()) { files.addIfNotAlreadyThere (f); if (f.getChildFile ("modules").isDirectory()) files.addIfNotAlreadyThere (f.getChildFile ("modules")); } } return files; }
void Initializer::initDaemon() const { if (FLAGS_config_check) { // No need to daemonize, emit log lines, or create process mutexes. return; } #if !defined(__APPLE__) && !defined(WIN32) // OS X uses launchd to daemonize. if (osquery::FLAGS_daemonize) { if (daemon(0, 0) == -1) { shutdown(EXIT_FAILURE); } } #endif // Print the version to the OS system log. systemLog(binary_ + " started [version=" + kVersion + "]"); if (!FLAGS_ephemeral) { if ((Flag::isDefault("pidfile") || Flag::isDefault("database_path")) && !isDirectory(OSQUERY_HOME)) { std::cerr << CONFIG_ERROR; } // Create a process mutex around the daemon. auto pid_status = createPidFile(); if (!pid_status.ok()) { LOG(ERROR) << binary_ << " initialize failed: " << pid_status.toString(); shutdown(EXIT_FAILURE); } } // Nice ourselves if using a watchdog and the level is not too permissive. if (!FLAGS_disable_watchdog && FLAGS_watchdog_level >= 0) { // Set CPU scheduling I/O limits. setToBackgroundPriority(); #ifdef __linux__ // Using: ioprio_set(IOPRIO_WHO_PGRP, 0, IOPRIO_CLASS_IDLE); syscall(SYS_ioprio_set, IOPRIO_WHO_PGRP, 0, IOPRIO_CLASS_IDLE); #elif defined(__APPLE__) setiopolicy_np(IOPOL_TYPE_DISK, IOPOL_SCOPE_PROCESS, IOPOL_THROTTLE); #endif } }
void recTree(std::string currentPath, std::set<std::string>& fullList, const std::string& exportroot) { if (fileExists(currentPath.c_str())) { // fs::path bRoot(exportroot); // fs::path bPath(currentPath); std::string stripstr = currentPath.substr(exportroot.length()); // LOGI((std::string("recTree: ") + stripstr).c_str()); fullList.insert(stripstr); if (isDirectory(currentPath.c_str())) { // fs::is_directory(bPath.string())) { DIR* d; if (currentPath.at(currentPath.length() - 1) != '/') currentPath += "/"; // LOGI((std::string("currentPath: ") + currentPath).c_str()); if ((d = opendir(currentPath.c_str())) == NULL) return; struct dirent* de; while ((de = readdir(d)) != NULL) { std::string path = currentPath; if (std::string(de->d_name) != "." && std::string(de->d_name) != "..") { path += std::string(de->d_name); // LOGI((std::string("path: ") + path).c_str()); recTree(path, fullList, exportroot); } } closedir(d); } else { // currentPath ends with "/" std::string parent = parentDirectory(currentPath); if (parent == "") { // Add parent dirs of current file down to root while (parent != exportroot) { std::string strippar = parent.substr(exportroot.length()); fullList.insert(strippar); // LOGI((std::string("Adding parent ") + parent.string()).c_str()); parent = parentDirectory(parent); } } } } }
int CountAllSubDirectories(const char* path) { int counter=1; int fileNameSize; char newPath[255]; DIR *pathDir; struct dirent *pathDirent; pathDir = opendir (path); if (pathDir == NULL) { fprintf (stderr,"Cannot open directory '%s'\n", path); exit(0); } while ((pathDirent = readdir(pathDir)) != NULL ) { strcpy(newPath,path); fileNameSize=strlen(pathDirent->d_name); if(pathDirent->d_name[0]!='.' && pathDirent->d_name[fileNameSize-1]!='~') { strcat(newPath,"/"); strcat(newPath,pathDirent->d_name); } if(isDirectory(newPath) && pathDirent->d_name[0]!='.' && pathDirent->d_name[fileNameSize-1]!='~') { counter+=CountAllSubDirectories(newPath); } } closedir (pathDir); return counter; }
bool SDCardEntry::findFile(const char *name, struct fat_dir_entry_struct *entry) { if (!isDirectory()) return false; fat_dir_struct *dd = fat_open_dir(SDCard.fs, &dir_entry); if (dd == NULL) return false; while (fat_read_dir(dd, entry)) { if (strcmp(entry->long_name, name) == 0) { fat_close_dir(dd); return true; } } fat_close_dir(dd); return false; }
void treatDir(const char * dirname, CONFIG options) { if (options.verbose) printf("Entering directory %s%s", options.infolder, dirname); DIR *dir; char inbuf[MAX_PATH] = ""; char outbuf[MAX_PATH] = ""; char recursdir[MAX_PATH] = ""; strcpy(inbuf, options.infolder); strcat(inbuf, dirname); struct dirent *dp; dir = opendir(inbuf); while ((dp=readdir(dir)) != NULL) { printf("debug: %s\n", dp->d_name); if ( !strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..") ) { // do nothing (straight logic) continue; } strcpy(recursdir, dirname); strcat(recursdir, dp->d_name); strcpy(inbuf, options.infolder); strcat(inbuf, dirname); strcat(inbuf, dp->d_name); strcpy(outbuf, options.outfolder); strcat(outbuf, dirname); strcat(outbuf, dp->d_name); if (isDirectory(inbuf)) { #if defined(_WIN32) _mkdir(outbuf); #else mkdir(outbuf, 0700); #endif strcat(recursdir, PATH_SEPARATOR); treatDir(recursdir, options); } else { process_file(inbuf, outbuf, options); } } closedir(dir); }
int countAllFiles(char* startingPath, char* extFilter) { int filesToPatchCount = 0; // Opens the current dir DIR* pDir = opendir (startingPath); struct dirent *pDirent; if (pDir == NULL) { printf ("Cannot open directory: '%s'\n", startingPath); exit(1); } char completePath[MAX_PATH]; // Writes all the file names in this dir, into the file while ((pDirent = readdir(pDir)) != NULL) { char* fileOrFolder = pDirent->d_name; //Makes sure it doesn't write stuff like "." or ".." into the file if((strcmpi(fileOrFolder,".") != 0) && (strcmpi(fileOrFolder,"..") != 0)) { //Creates the complete path (E.g. from C:\folder goes to c:\folder\something) strcpy(completePath,startingPath); strcat(completePath,fileOrFolder); if (isDirectory(completePath)) { /* If the path was something like c:\folder\something, since it's a folder, we add: c:\folder\something\ */ strcat(completePath,"\\"); filesToPatchCount += countAllFiles(completePath, extFilter); } else { filesToPatchCount++; } } } //Closes the dir and the file closedir (pDir); return filesToPatchCount; }
/*! * @brief プログラムのエントリポイント * @param [in] argc コマンドライン引数の数 * @param [in] argv コマンドライン引数 * @return 終了ステータス */ int main(int argc, char *argv[]) { std::string lang = DEFAULT_LANG; int remidx = parseArguments(argc, argv, lang); if (argc == remidx) { // 引数のチェック std::cerr << "Invalid argument" << std::endl; showUsage(argv[0], EXIT_FAILURE); } try { std::vector<std::string> arg_list; for (int i = remidx; i < argc; i++) { arg_list.push_back(argv[i]); } clx::http session(clx::uri::encode(URL_HOST), HTTP_PORT); for (std::vector<std::string>::iterator arg = arg_list.begin(); arg != arg_list.end(); ++arg) { if (isDirectory(*arg)) { // ディレクトリだった場合 std::vector<std::string> file_list = getFileList(*arg); for (std::vector<std::string>::iterator fn = file_list.begin(); fn != file_list.end(); ++fn) { if (checkSuffix(*fn, "wav")) { std::cout << *fn << " ... "; try { speachToText(session, lang, *fn, *fn + ".txt"); std::cout << "Proccessed" << std::endl; } catch (const char *errmsg) { std::cerr << errmsg << std::endl; } } } } else { // ファイルだった場合 std::cout << *arg << " ... "; try { speachToText(session, lang, *arg, *arg + ".txt"); std::cout << "Proccessed" << std::endl; } catch (const char *errmsg) { std::cerr << errmsg << std::endl; } } } } catch (clx::socket_error &e) { std::cerr << e.what() << std::endl; } return EXIT_SUCCESS; }
//============================================================================ // FUNCTION : SPELLutils::getSubdirs //============================================================================ std::list<std::string> SPELLutils::getSubdirs( const std::string& path ) { DIR* dirp; struct dirent *dp; std::string dot = "."; std::string pdot = ".."; std::string svn = ".svn"; std::list<std::string> subdirs; dirp = opendir( path.c_str() ); if (dirp) { while ( (dp = readdir(dirp)) != NULL ) { if (dp->d_type & DT_DIR) { if ( dp->d_name != dot && dp->d_name != pdot && dp->d_name != svn ) { subdirs.push_back(dp->d_name); } } // IMPORTANT: in some filesystems, the type may be impossible // to get with readdir. In these cases we need to use stat(). else if (dp->d_type == DT_UNKNOWN) { if ( isDirectory( path + PATH_SEPARATOR + std::string(dp->d_name) ) ) { if ( dp->d_name != dot && dp->d_name != pdot && dp->d_name != svn ) { subdirs.push_back(dp->d_name); } } } // Ignore other types like symbolic links, sockets, etc. } closedir(dirp); } else { LOG_ERROR("Failed to open directory '" + path + "' to get subdirs"); } return subdirs; }
/** \brief Sets the storage method field for the entry. * * This function sets the method with which the file data is to * be compressed. * * The method is ignored in a file entry which cannot be compressed. * (or more precisly, the method is forced as STORED.) * * \exception InvalidStateException * This exception is raised if the \p method parameter does not represent * a supported method. At this time the library only supports STORED and * DEFLATED. The getMethod() may return more types as read from a Zip * archive, but it is not possible to set such types using this function. * * \param[in] method The method field is set to the specified value. */ void FileEntry::setMethod(StorageMethod method) { switch(method) { case StorageMethod::STORED: //case StorageMethod::SHRUNK: //case StorageMethod::REDUCED1: //case StorageMethod::REDUCED2: //case StorageMethod::REDUCED3: //case StorageMethod::REDUCED4: //case StorageMethod::IMPLODED: //case StorageMethod::TOKENIZED: case StorageMethod::DEFLATED: //case StorageMethod::DEFLATED64: //case StorageMethod::OLD_TERSE: //case StorageMethod::RESERVED11: //case StorageMethod::BZIP2: //case StorageMethod::REVERVED13: //case StorageMethod::LZMA: //case StorageMethod::RESERVED15: //case StorageMethod::RESERVED16: //case StorageMethod::RESERVED17: //case StorageMethod::NEW_TERSE: //case StorageMethod::LZ77: //case StorageMethod::WAVPACK: //case StorageMethod::PPMD_I_1: break; default: throw InvalidStateException("unknown method"); } if(isDirectory()) { // force uncompressed for directories m_compress_method = StorageMethod::STORED; } else { m_compress_method = method; } }
/** \brief Define the level of compression to use by this FileEntry. * * This function saves the level of compression the library should use * to compress the file before saving it in the output file. * * \note * If the StorageMethod is set to STORED, then the compression level is * ignored, but it is left unchanged. * * \exception InvalidStateException * This function raises this exception if the specified level is out of * the allowed range. * * \param[in] level The compression level to use to compress the file data. */ void FileEntry::setLevel(CompressionLevel level) { if(level < COMPRESSION_LEVEL_DEFAULT || level > COMPRESSION_LEVEL_MAXIMUM) { throw InvalidStateException("level must be between COMPRESSION_LEVEL_DEFAULT and COMPRESSION_LEVEL_MAXIMUM"); } if(isDirectory()) { if(level >= COMPRESSION_LEVEL_MINIMUM) { throw InvalidStateException("directories cannot be marked with a compression level other than COMPRESSION_LEVEL_NONE (defaults will also work"); } m_compression_level = COMPRESSION_LEVEL_NONE; } else { m_compression_level = level; } }
QIcon Location::getIcon() const { // TODO: So far only Linux can provide icons for remote files without pooping its pants. // do something nicer for Windows. switch ( mData->mProtocol ) { case Local: return sIconProvider->icon( QFileInfo( mData->mPath ) ); case Ssh: case Sftp: if ( isDirectory() ) { return sIconProvider->icon( QFileIconProvider::Folder ); } else { return sIconProvider->icon( QFileIconProvider::File ); } default: return QIcon(); } }
int indexerValidateArgs(int argc, char** argv) { if ((argc != 3) && (argc != 5)) { printf("Incorrect entry of arguments! Indexer requires: \n"); printf("Usage: [./indexer] [DATA DIR] [DATA FILENAME] \n"); printf("TEST MODE: [./indexer] [DATA DIR] [TEST INDEX FILE] [TEST INFILE] [TEST OUTFILE]\n"); printf("You entered: %d", argc); return 1; } if (!isDirectory(argv[1])) { printf("Error: the dir argument was not found. Please enter writable and valid\ directory.\n"); return 1; }
bool INotifyEventPublisher::isPathMonitored(const std::string& path) { boost::filesystem::path parent_path; if (!isDirectory(path).ok()) { if (path_descriptors_.find(path) != path_descriptors_.end()) { // Path is a file, and is directly monitored. return true; } if (!getDirectory(path, parent_path).ok()) { // Could not get parent of unmonitored file. return false; } } else { parent_path = path; } // Directory or parent of file monitoring auto path_iterator = path_descriptors_.find(parent_path.string()); return (path_iterator != path_descriptors_.end()); }
/* * Checks if there are arguments problems * * @return 0 if there are no problems, 1 otherwise. * */ int checkArguments(){ int c,err = 0; int response; while ((c = getopt(g_argc, g_argv, "qr")) != -1){ switch (c) { case 'q': qflag = 1; break; case 'r': rflag = 1; break; case '?': err = 1; break; } } if((optind+2) > g_argc){ fprintf(stderr, "At least two arguments must be introduced.\n"); return -1; }else if (err){ fprintf(stderr, "Given options are invalid..\n"); return -1; } if (!checkExistence(g_argv[g_argc-1])) { fprintf(stderr, "Given directory doesn't exist. [%s]\n", g_argv[g_argc-1]); return -1; } if (!isDirectory(g_argv[g_argc-1])) { fprintf(stderr, "Last argument is not a directory. [%s]\n", g_argv[g_argc-1]); return -1; } return 0; }