Exemplo n.º 1
0
void CmdDoc::list()
{
  if(!mCmd->parmCount())
  {
    if(!loadFileNames()) return;
    listFiles();
    while(lessFile()) {} // Nothing todo in block
  }
  else
  {
    QString parm = mCmd->parmStr(1);
    int fileNumber = parm.toInt();

    if(!fileNumber)
    {
      if(!loadFileNames(parm)) return;
      if(mAllFiles.size() == 1)
      {
        lessFile(mAllFiles.keys().at(0));
      }
      else
      {
        listFiles();
        while(lessFile()) {} // Nothing todo in block
      }
    }
    else
    {
      if(!loadFileNames()) return;
      lessFile(fileNumber);
    }
  }
}
Exemplo n.º 2
0
void playMenuLoadLevelButtonFunction(sguiButton_struct* b)
{
	testTransition=startCameraTransition(&cameraStates[1],&cameraStates[3],64);
	setupMenuPage(selectLevelMenuPage, selectLevelMenuPageLength);

	testListCnt=0;
	testListCnt1=0;

	testListCnt1=testListCnt+=listFiles("./maps", NULL);
	#ifndef FATONLY
		char str[255]; 
		sprintf(str,"%s/%s/maps",basePath,ROOT);
		testListCnt+=listFiles(str, NULL);
	#endif

	testList=malloc(sizeof(char*)*testListCnt);

	listFiles("./maps", testList);
	#ifndef FATONLY
		listFiles(str, &testList[testListCnt1]);
	#endif

	initScreenList(&testScreenList, "Select level", testList, testListCnt);
	updateScreenList(&testScreenList);
}
Exemplo n.º 3
0
int
main(int argc, char *argv[])
{
    if (argc > 1 && strcmp(argv[1], "--help") == 0)
        usageErr("%s [dir-path...]\n", argv[0]);

    if (argc == 1)              /* No arguments - use current directory */
        listFiles(".");
    else
        for (argv++; *argv; argv++)
            listFiles(*argv);

    exit(EXIT_SUCCESS);
}
Exemplo n.º 4
0
//Process a Request
void processRequest(char * buf){

    char token[64] = "";

    // Check Command
    if (strncmp(buf, "GET", 3) == 0) {
        //Token File Name
        printf("GET CALLED!\n");
        //Call Get Function
        strtok(buf, " ");
        strcpy(token, strtok(NULL, "\n"));
        getFile(token);
    } else if(strncmp(buf, "LIST", 4) == 0) {
        //List Call
        listFiles();
    } else if((strncmp(buf, "PUT", 3) == 0)) {
        printf("PUT Called!\n");
        if (userVerified){
            strtok(buf, " ");
            strcpy(token, strtok(NULL, "\n"));
            putFile(token);
        } else {
            printf("User not Verified! Please Enter the Corret Credentials!\n");
        }

    } else {
        printf("Unsupported Command: %s\n", buf);
        return;
    }
}
Exemplo n.º 5
0
CZipLoader::CZipLoader(const std::string & mountPoint, const std::string & archive):
    archiveName(archive),
    mountPoint(mountPoint),
    files(listFiles(mountPoint, archive))
{
	logGlobal->traceStream() << "Zip archive loaded, " << files.size() << " files found";
}
Exemplo n.º 6
0
int main(int argc, char **argv) {
	std::vector<Common::UString> args;
	Common::Platform::getParameters(argc, argv, args);

	int returnValue = 1;
	Command command = kCommandNone;
	Common::UString file;

	try {
		if (!parseCommandLine(args, returnValue, command, file))
			return returnValue;

		Aurora::HERFFile herf(new Common::ReadFile(file));

		if      (command == kCommandList)
			listFiles(herf);
		else if (command == kCommandExtract)
			extractFiles(herf);

	} catch (Common::Exception &e) {
		Common::printException(e);
		return -1;
	} catch (std::exception &e) {
		error("%s", e.what());
	}

	return 0;
}
Exemplo n.º 7
0
/** Removes a directory (including all files contained). The function could
 *  easily recursively delete further subdirectories, but this is commented
 *  out atm (to limit the amount of damage in case of a bug).
 *  \param name Directory name to remove.
 *  \param return True if removal was successful.
 */
bool FileManager::removeDirectory(const std::string &name) const
{
    std::set<std::string> files;
    listFiles(files, name, /*is full path*/ true);
    for(std::set<std::string>::iterator i=files.begin(); i!=files.end(); i++)
    {
        if((*i)=="." || (*i)=="..") continue;
        if(UserConfigParams::logMisc())
            Log::verbose("FileManager", "Deleting directory '%s'.",
                         (*i).c_str());
        if(isDirectory(*i))
        {
            // This should not be necessary (since this function is only
            // used to remove addons), and it limits the damage in case
            // of any bugs - i.e. if name should be "/" or so.
            // removeDirectory(full_path);
        }
        else
        {
            removeFile(*i);
        }
    }
#if defined(WIN32)
        return RemoveDirectory(name.c_str())==TRUE;
#else
    return remove(name.c_str())==0;
#endif
}   // remove directory
Exemplo n.º 8
0
int main(int argc, char **argv) {
	std::vector<Common::UString> args;
	Common::Platform::getParameters(argc, argv, args);

	int returnValue = 1;
	Command command = kCommandNone;
	Common::UString file;

	try {
		if (!parseCommandLine(args, returnValue, command, file))
			return returnValue;

		Aurora::NDSFile nds(new Common::ReadFile(file));

		if      (command == kCommandInfo)
			displayInfo(nds);
		else if (command == kCommandList)
			listFiles(nds);
		else if (command == kCommandExtract)
			extractFiles(nds);

	} catch (...) {
		Common::exceptionDispatcherError();
	}

	return 0;
}
	unsigned __stdcall serviceDataThread( void* pArguments ){
		ListenSocket * clientDataSocket;
		ClientThreadResource * res = (ClientThreadResource*) pArguments;
		clientDataSocket = acceptRequest(res->dataSocket);
		
		if(res->mode == FTP_DATA_MODE_PASIVE){
			
			if ( res->transferTask == STOR_TRANSFER ){
				storeFile( res , clientDataSocket );
			} else if ( res->transferTask == RETR_TRANSFER ){
				retrieveFile( res , clientDataSocket );
			} else if ( res->transferTask == LIST_TRANSFER ){
				listFiles( res , clientDataSocket );
			}
			
		}else if(res->mode == FTP_DATA_MODE_ACTIVE){
			
			while(res->mode == FTP_DATA_MODE_ACTIVE){		
				
				blockMutex(res->dataMutex );
				executeActiveCommand(res);
				//unblockMutex(res->controlMutex);
			}			
		}

		res->mode = FTP_DATA_MODE_INACTIVE;
		_endthread();
	}
Exemplo n.º 10
0
/*!
  Implementation for traverse so always true.
*/
bool FileFixture::execute(void * objectInstance, QString actionName, QHash<QString, QString> parameters, QString & stdOut)
{
    Q_UNUSED(objectInstance);

    TasLogger::logger()->debug("> FileFixture::execute:" + actionName);

    if (actionName == "read_file") {
        readFile(parameters.value(FILE_NAME), stdOut);
    }else if (actionName == "read_file_part") {
        readFilePart(parameters.value(FILE_NAME),parameters.value(FILE_OFFSET).toInt(),parameters.value(DATA_LENGHT).toInt(), stdOut);
    } else if(actionName == "write_file") {
        writeFile(parameters.value(FILE_NAME), parameters.value(FILE_DATA), stdOut);
    } else if(actionName == "write_file_append") {
        writeFileAppend(parameters.value(FILE_NAME), parameters.value(FILE_DATA),parameters.value(FILE_OFFSET).toInt(),parameters.value(DATA_LENGHT).toInt(), stdOut);
    } else if(actionName == "delete_file") {
        deleteFile(parameters.value(FILE_NAME), stdOut);
    } else if(actionName == "mk_dir") {
        mkDir(parameters.value(FILE_NAME), stdOut);
    } else if(actionName == "rm_dir") {
        rmDir(parameters.value(FILE_NAME), stdOut);
    } else if(actionName == "list_files") {
        listFiles(parameters.value(FILE_PATH), parameters.value(FILE_NAME), stdOut);
    }

    return true;
}
Exemplo n.º 11
0
int main(int argc, char **argv) {
	std::vector<Common::UString> args;
	Common::Platform::getParameters(argc, argv, args);

	Aurora::GameID game = Aurora::kGameIDUnknown;

	int returnValue = 1;
	Command command = kCommandNone;
	Common::UString file;

	try {
		if (!parseCommandLine(args, returnValue, command, file, game))
			return returnValue;

		Aurora::RIMFile rim(new Common::ReadFile(file));

		if      (command == kCommandList)
			listFiles(rim, game);
		else if (command == kCommandExtract)
			extractFiles(rim, game);

	} catch (...) {
		Common::exceptionDispatcherError();
	}

	return 0;
}
Exemplo n.º 12
0
void listFiles(const Path& parent, std::list<Path> & list) throw (OpenFileException)
{
    INFO("Adding: %s", parent.fullPath.c_str());
    list.push_back(parent);

    if (!parent.isDir)
        return;

    INFO("Listing files for: %s", parent.fullPath.c_str());
    DIR* directory = 0;
    struct dirent* entry = 0;

    if ((directory = opendir(parent.fullPath.c_str())) == NULL)
    {
        WARN("%s", "Cant open the directory.");
        throw OpenFileException(parent.fullPath.c_str(), CAN_NOT_OPEN_INPUT_FILE);
    }

    while ((entry = readdir(directory)))
    {
        bool isNotCurrentOrParentDirectory = strncmp(entry->d_name, "..", 2) != 0 &&
                strncmp(entry->d_name, ".", 1) != 0;

        if (isNotCurrentOrParentDirectory)
        {
            bool isDir = entry->d_type == DT_DIR;
            Path path(parent, entry->d_name, isDir);
            listFiles(path, list);
        }
    }

    closedir(directory);
}
Exemplo n.º 13
0
bool Tune::begin()
{
	// Pin configuration
	pinMode(DREQ, INPUT_PULLUP);
	pinMode(XDCS, OUTPUT);
	pinMode(XCS, OUTPUT);
	pinMode(SDCS, OUTPUT);
	
	// Deselect control & data ctrl
	digitalWrite(XCS, HIGH);
	digitalWrite(XDCS, HIGH);
	// Deselect SD's chip select
	digitalWrite(SDCS, HIGH);
	
	// SD card initialization
	if (!sd.begin(SDCS, SPI_HALF_SPEED))
	{
		sd.initErrorHalt(); // describe problem if there's one
		return 0; 
	}
	
	// Tracklisting also return the number of playable files
	Serial.print(listFiles());
	Serial.print(" tracks found, ");
	
	// SPI bus initialization
	SPI.begin();
	SPI.setDataMode(SPI_MODE0);
	// Both SCI and SDI read data MSB first
	SPI.setBitOrder(MSBFIRST);
	// From the datasheet, max SPI reads are CLKI/6. Here CLKI = 26MHz -> SPI max speed is 4.33MHz.
	// We'll take 16MHz/4 = 4MHz to be safe.
	// Plus it's the max recommended speed when using a resistor-based lvl converter with an SD card.
	SPI.setClockDivider(SPI_CLOCK_DIV4);
	SPI.transfer(0xFF);
	delay(10);
	
	// Codec initialization
	// Software reset
	setBit(SCI_MODE, SM_RESET);
	delay(5);
	// VS1022 "New mode" activation
	setBit(SCI_MODE, SM_SDINEW);
	// Clock setting (default is 24.576MHz)
	writeSCI(SCI_CLOCKF, 0x32, 0xC8);
	delay(5);
	
	// Wait until the chip is ready
	while (!digitalRead(DREQ));
	delay(100);
	
	// Set playState flag
	playState = idle;
	
	// Set volume to avoid hurt ears ;)
	setVolume(150);
	
	Serial.println("Tune ready !");
	return 1;
}
Exemplo n.º 14
0
int main(int argc, char **argv) {
    try {
        std::vector<Common::UString> args;
        Common::Platform::getParameters(argc, argv, args);

        Aurora::GameID game = Aurora::kGameIDUnknown;

        int returnValue = 1;
        Command command = kCommandNone;
        Common::UString archive;
        std::set<Common::UString> files;
        std::vector<byte> password;

        if (!parseCommandLine(args, returnValue, command, archive, files, game, password))
            return returnValue;

        Aurora::ERFFile erf(new Common::ReadFile(archive), password);

        if      (command == kCommandInfo)
            displayInfo(erf);
        else if (command == kCommandList)
            listFiles(erf, game);
        else if (command == kCommandListVerbose)
            listVerboseFiles(erf, game);
        else if (command == kCommandExtract)
            extractFiles(erf, game, files, kExtractModeStrip);
        else if (command == kCommandExtractSub)
            extractFiles(erf, game, files, kExtractModeSubstitute);

    } catch (...) {
        Common::exceptionDispatcherError();
    }

    return 0;
}
Exemplo n.º 15
0
/**
 * This function is recursive and will call itself to list files in any
 * subfolders found.
 */
void listFiles(const std::string& idPrefix, const std::string& path,
	ga::Archive& archive, bool bScript)
{
	std::string prefix = idPrefix;
	if (!idPrefix.empty()) prefix.append(".");

	int j = 0;
	for (const auto& i : archive.files()) {
		int len = path.length() + i->strName.length();
		if (i->fAttr & ga::Archive::File::Attribute::Folder) {
			// This is a folder, not a file
			if (bScript) {
				std::cout << "index=" << prefix << j << ";path=" << path
					<< ';' << i->getContent() << std::endl;
			} else {
				std::cout << "@" << prefix << j << "\t" << path << i->strName << '/';
				len++; // because of trailing slash we just added
				if (len < 25) std::cout << std::string(25 - len, ' ');
				std::cout << "[dir";
				if (i->fAttr & ga::Archive::File::Attribute::Hidden) std::cout << "; hidden";
				if (i->fAttr & ga::Archive::File::Attribute::Compressed) std::cout << "; compressed";
				if (i->fAttr & ga::Archive::File::Attribute::Encrypted) std::cout << "; encrypted";
				std::cout << "]\n";
			}
			auto subArch = archive.openFolder(i);
			listFiles(
				createString(prefix << j),
				createString(path << i->strName << '/'),
				*subArch,
				bScript
			);
		} else {
			if (bScript) {
				std::cout << "index=" << prefix << j << ";path=" << path
					<< ';' << i->getContent() << std::endl;
			} else {
				std::cout << "@" << prefix << j << "\t" << path << i->strName;
				// Pad the filename out to 25 chars if it's short enough
				if (len < 25) std::cout << std::string(25 - len, ' ');

				std::cout << "[";

				// Display the "MIME" type if there is one
				if (!i->type.empty()) std::cout << i->type << "; ";

				/// Display any attributes
				if (i->fAttr & ga::Archive::File::Attribute::Vacant) std::cout << "empty slot; ";
				if (i->fAttr & ga::Archive::File::Attribute::Hidden) std::cout << "hidden; ";
				if (i->fAttr & ga::Archive::File::Attribute::Compressed) std::cout << "compressed; ";
				if (i->fAttr & ga::Archive::File::Attribute::Encrypted) std::cout << "encrypted; ";

				// Display file size
				std::cout << i->storedSize << " bytes]\n";
			}
		}
		j++;
	}
	return;
}
Exemplo n.º 16
0
void explorePath(const char* path, std::list<Path>& files)throw (FileException)
{
    INFO("Explore path: %s", path);
    checkPath(path);
    bool isDir = isDirectory(path);
    Path file(path, isDir);
    listFiles(file, files);
}
Exemplo n.º 17
0
extern "C" void __declspec(dllexport) CALLBACK RunTests(HWND hwnd, HINSTANCE hinst, LPSTR lpszCmdLine, int nCmdShow)
{
	InitConsole();

	std::cout << "cmd-line: " << lpszCmdLine << std::endl;
	std::cout << "Running test listFiles on file " << lpszCmdLine << ":" << std::endl;
	listFiles(lpszCmdLine);
	system("PAUSE");
}
Exemplo n.º 18
0
int main(int argc, char *argv[]) 
{
   int rightOrWrong;
   printf("Content-type: text/html\n\n");
   
   printf("<br><table width=\"860\" border=0 cellspacing='4'>\n");
   printf("<tr><td width=\"50%%\"><b>Correctly Tagged</b></td><td width=\"50%%\"><b>Incorrectly Tagged</b></td></tr>\n");
   printf("<tr><td valign=top>\n");

   rightOrWrong = 0;
   listFiles(rightOrWrong);
   printf("</td><td valign=top>\n");
   rightOrWrong = 1;
   listFiles(rightOrWrong);
   printf("</td></tr></table>\n");


}
Exemplo n.º 19
0
///CZipLoader
CZipLoader::CZipLoader(const std::string & mountPoint, const boost::filesystem::path & archive, std::shared_ptr<CIOApi> api):
	ioApi(api),
    zlibApi(ioApi->getApiStructure()),
    archiveName(archive),
    mountPoint(mountPoint),
    files(listFiles(mountPoint, archive))
{
	logGlobal->traceStream() << "Zip archive loaded, " << files.size() << " files found";
}
Exemplo n.º 20
0
//-----------------------------------------------------------------------------
FileManager::~FileManager()
{
    // Clean up left-over files in addons/tmp that are older than 24h
    // ==============================================================
    // (The 24h delay is useful when debugging a problem with a zip file)
    std::set<std::string> allfiles;
    std::string tmp=getAddonsFile("tmp");
    listFiles(allfiles, tmp);
    for(std::set<std::string>::iterator i=allfiles.begin();
        i!=allfiles.end(); i++)
    {
        if((*i)=="." || (*i)=="..") continue;
        // For now there should be only zip files or .part files
        // (not fully downloaded files) in tmp. Warn about any
        // other files.
        std::string full_path=tmp+"/"+*i;
        if(StringUtils::getExtension(*i)!="zip" &&
           StringUtils::getExtension(*i)!="part"    )
        {
            Log::warn("[FileManager]", "Unexpected tmp file '%s' found.",
                       full_path.c_str());
            continue;
        }
        if(isDirectory(full_path))
        {
            // Gee, a .zip file which is a directory - stay away from it
            Log::warn("[FileManager]", "'%s' is a directory and will not be deleted.",
                      full_path.c_str());
            continue;
        }
        struct stat mystat;
        stat(full_path.c_str(), &mystat);
        StkTime::TimeType current = StkTime::getTimeSinceEpoch();
        if(current - mystat.st_ctime <24*3600)
        {
            if(UserConfigParams::logAddons())
                Log::verbose("[FileManager]", "'%s' is less than 24h old "
                             "and will not be deleted.",
                             full_path.c_str());
            continue;
        }
        if(UserConfigParams::logAddons())
            Log::verbose("[FileManager]", "Deleting tmp file'%s'.",full_path.c_str());
        removeFile(full_path);

    }   // for i in all files in tmp

    // Clean up rest of file manager
    // =============================
    popMusicSearchPath();
    popModelSearchPath();
    popTextureSearchPath();
    popTextureSearchPath();
    m_file_system->drop();
    m_file_system = NULL;
}   // ~FileManager
Exemplo n.º 21
0
void createMenuLoadLevelButtonFunction(sguiButton_struct* b)
{
	testTransition=startCameraTransition(&cameraStates[2],&cameraStates[3],64);
	setupMenuPage(loadLevelMenuPage, loadLevelMenuPageLength);

	testListCnt=0;
	testListCnt1=0;

	char str[255]; 
	sprintf(str,"%s/%s/maps",basePath,ROOT);
	testListCnt1=testListCnt+=listFiles(str, NULL);

	testList=malloc(sizeof(char*)*testListCnt);

	listFiles(str, testList);

	initScreenList(&testScreenList, "Load level", testList, testListCnt);
	updateScreenList(&testScreenList);
}
Exemplo n.º 22
0
/*
 * LIST FILES : SERVER SIDE
 *
 * Handle the server side of the list files funcitonality
 */ 
int serverListFiles(BIO *conn, int clientid) {
	//send the client a single string listing all files
	//in the folder
	char buffer[BUFFER_SIZE];
	if(listFiles(buffer, sizeof(buffer), clientid) == -1) return -1;

	if(writeString(conn, buffer) < 1) return -1;

	return 1;
}
Exemplo n.º 23
0
bool InvokeJavascript_OneArg(NPObject *npobj, const char *methodName, const NPVariant &arg, NPVariant *&result) {
  if (!(NPVARIANT_IS_STRING(arg))) {
    return false;
  }

  bool success = false;

  const char *argStringValue = stringFromNpVariant(arg);

  if (!strcmp(methodName, "fileExists")) {
    //fileExists(filename : string) : bool
    success = SetReturnValue(fileExists(argStringValue), *result);
  } else if (!strcmp(methodName, "isDirectory")) {
    //isDirectory(filename : string) : bool
    success = SetReturnValue(isDirectory(argStringValue), *result);
  } else if (!strcmp(methodName, "createDirectory")) {
    if (!createDirectory(argStringValue)) {
      //TODO: Throw a particular exception
      success = false;
    } else {
      success = true;
    }
  } else if (!strcmp(methodName, "getTextFile")) {
    //getTextFile(filename : string) : string
    char *value = NULL;
    size_t len = 0;
    if (getFile(argStringValue, value, len, false)) {
      success = SetReturnValue(value, len, *result);
      delete[] value;
    }
  } else if (!strcmp(methodName, "getBinaryFile")) {
    //getBinaryFile(filename : string) : array<byte>
    char *value = NULL;
    size_t len = 0;
    if (getFile(argStringValue, value, len, true)) {
      success = SetArrayReturnValue(value, len, GetInstance(npobj), result);
      delete[] value;
    }
  } else if (!strcmp(methodName, "removeFile")) {
    //removeFile(filename : string) : void
    success = removeFile(argStringValue);
  } else if (!strcmp(methodName, "listFiles")) {
    //listFiles(filename : string) : array<object>
    std::vector<FileEntry *> *entries;
    if (listFiles(argStringValue, entries)) {
      success = SetArrayReturnValue(*entries, GetInstance(npobj), result);
      deleteFileEntries(entries);
    } else {
      success = false;
    }
  }

  delete[] argStringValue;
  return success;
}
Exemplo n.º 24
0
	void impl_walkFiles(std::string const& _basedir, std::string const& _dir, std::function<void(std::string)> _func) {
		auto files = listFiles(_basedir+_dir);
		for (auto const& f : files) {
			_func(_dir + f);
		}
		auto dirs = listDirs(_basedir+_dir);
		for (auto const& d : dirs) {
			if (d != "." && d!= "..") {
				impl_walkFiles(_basedir, _dir + d + "/", _func);
			}
		}
	}
Exemplo n.º 25
0
 BSONObj ls(const BSONObj& args) { 
     BSONObj o = listFiles(args);
     if( !o.isEmpty() ) {
         for( BSONObj::iterator i = o.firstElement().Obj().begin(); i.more(); ) { 
             BSONObj f = i.next().Obj();
             cout << f["name"].String();
             if( f["isDirectory"].trueValue() ) cout << '/';
             cout << '\n';
         }
         cout.flush();
     }
     return BSONObj();
 }
Exemplo n.º 26
0
void listDirectory(AtMegaWebServer& web_server, SdBaseFile* file)
{
  const char* path =  web_server.get_path();
  web_server.sendHttpResult(200);

  Client& client = web_server.get_client();
  web_server << F("<html><head><title>");
  web_server << (path);
  web_server << F("</title></head><body><h1>");
  web_server << (path);
  web_server << F("</h1><hr><pre>");
  listFiles(path, file, &client, LS_DATE | LS_SIZE);
  web_server << F("</pre><hr></body></html>\n");
}
Exemplo n.º 27
0
BSONObj ls(const BSONObj& args, void* data) {
    BSONArrayBuilder ret;
    BSONObj o = listFiles(args, data);
    if (!o.isEmpty()) {
        for (BSONObj::iterator i = o.firstElement().Obj().begin(); i.more();) {
            BSONObj f = i.next().Obj();
            string name = f["name"].String();
            if (f["isDirectory"].trueValue()) {
                name += '/';
            }
            ret << name;
        }
    }
    return BSON("" << ret.arr());
}
Exemplo n.º 28
0
bool listFiles(const filesystem::Folder &folder, std::string &ident)
{
	std::cout << ident << "Folder " << folder.getName() << ": " << std::endl;
	ident += "  ";

	for(const filesystem::File &file : folder.getFiles())
		std::cout << ident << "File " << file.getName() << std::endl;

	for(const filesystem::Folder &subfolder : folder.getFolders())
		listFiles(subfolder, ident);

	ident.erase(ident.length()-2, 2);
	std::cout << ident << "END Folder " << folder.getName() << std::endl;
	return true;
}
Exemplo n.º 29
0
/**
 * Returns list of files (and empty directories, if <code>listEmptyDirectories</code> is set)
 * found in the directory <code>directory</code>.
 *
 * @param directory full path of the directory.
 * @param relative should the returned file list be relative to the <code>directory</code>.
 *        Default value is <code>false</code>, meaning returned file listing has full
 *        file paths.
 * @param listEmptyDirectories should the returned file list contain also empty directories.
 *        Default value is <code>false</code>, meaning no empty directories are returned.
 * @param unixStyle should the returned file path entries in the file list use the unix style
 *        path separators. Default value is <code>false</code>, meaning operating system
 *        specific path separators are used.
 * @throws IOException throws exception if the directory listing failed.
 */
std::vector<std::string> digidoc::util::File::listFiles(const std::string& directory, bool relative,
		bool listEmptyDirectories, bool unixStyle) throw(IOException)
{
    // Why, oh why does this function use vectors, not std::lists? Does anybody need to do heavy random access on the file names?
	std::string pathDelim; pathDelim += PATH_DELIMITER;
	if(unixStyle)
	{
	    pathDelim = "/";
	}
    std::vector<std::string> files;

    // List entries in sub folders.
    std::vector<std::string> subDirectories = getDirSubElements(directory, true, false, unixStyle);
    std::vector<std::string>::const_iterator subDirectory = subDirectories.begin();
    for ( ; subDirectory != subDirectories.end(); subDirectory++ )
    {
        // Get files in sub directory.
        std::vector<std::string> list = listFiles(path(directory, *subDirectory), relative, listEmptyDirectories, unixStyle);

        if(!list.empty())
        {
            for(std::vector<std::string>::const_iterator iter = list.begin(); iter != list.end(); iter++)
            {
                if(relative)
                    files.push_back(path(*subDirectory, *iter, unixStyle));
                else
                	files.push_back(*iter);
            }
        }
        else
        {
        	if(listEmptyDirectories)
        	{
                if(relative)
                    files.push_back(std::string(*subDirectory) + pathDelim);
                else
                    files.push_back(path(directory, *subDirectory, unixStyle) + pathDelim);
        	}
        }
    }

    // List files directly in current directory
    std::vector<std::string> dirFiles = getDirSubElements(directory, relative, true, unixStyle);
    files.insert(files.begin(), dirFiles.begin(), dirFiles.end());

    return files;
}
Exemplo n.º 30
0
int main() {
	const char* FOLDER = "data/n2000/";

	avgCost = 0.0;
	avgTime = 0.0;

    std::vector<std::string> files = listFiles(FOLDER);

    for(int i = 0; i < files.size(); i++) {
    	run(FOLDER + files[i]);
    }
    
    printf("avg cost = %.10f\n", avgCost/files.size());
    printf("avg time = %.10f\n", avgTime/files.size());

	return 0;
}