Exemple #1
0
DWORD WINAPI download(PVOID param)
{
	filesCopied = 0;
	for (std::vector<LibraryItem *>::iterator it = libItems.begin(); it != libItems.end(); it++)
	{
		StringStream destination;
		LibraryItem *item = *it;

		String fromFile = *drivesList->getSelectedItem();
		fromFile += TEXT("iPod_Control\\Music\\");
		fromFile += *item->getContainer();

		String toFile = destPath;

		Regex pattern(TEXT("[*|\\\\:\"<>?/]|\\.+$"));
		String replace(TEXT(" "));
		Regex antispace(TEXT("^[[:s:]]+$|^\\s+|\\s+$"));
		String sp_replace(TEXT(""));

		String artist = std::tr1::regex_replace(*item->getArtist(), pattern, replace);
		String album = std::tr1::regex_replace(*item->getAlbum(), pattern, replace);
		if (std::tr1::regex_match(album, antispace))
			album = std::tr1::regex_replace(album, antispace, sp_replace);
		String file = std::tr1::regex_replace(*item->getFilename(), pattern, replace);

		toFile += *trim(&artist);

		if (!directoryExists(&toFile))
			CreateDirectory(toFile.c_str(), NULL);

		toFile += TEXT("\\");
		toFile += *trim(&album);

		if (!directoryExists(&toFile))
			CreateDirectory(toFile.c_str(), NULL);

		toFile += TEXT("\\");
		toFile += *trim(&file);

		if (!fileExists(&toFile)) {
			if (!CopyFile(fromFile.c_str(), toFile.c_str(), FALSE)) {
				StringStream err;
				err << "Could not copy file. Error " << GetLastError();
				String text = err.str();
				MessageBox(appWindow->getHandle(), text.c_str(), caption.c_str(), MB_ICONERROR | MB_OK);
				break;
			}
		}

		filesCopied++;
		StringStream *progr = new StringStream();
		*progr << filesCopied << TEXT(" / ") << totalFiles;
		String *cap = new String(progr->str());
		progress->setCaption(cap);
		delete cap;
		delete progr;
	}

	ExitThread(0);
}
 std::vector<std::string> getDirectoryListAsVector(const char *directory, const char *mask, bool caseSensitive)
 {
     if (!directoryExists(directory)) {
         return std::vector<std::string>{};
     }
     std::vector<std::string> returnVector;
     DIR *targetDirectory;
     struct dirent *entity;
     if ((targetDirectory = opendir(directory)) != nullptr) {
         while ((entity = readdir(targetDirectory)) != nullptr) {
             if (directoryExists(entity->d_name)) {
                 std::string maskCopy{static_cast<std::string>(mask)};
                 std::string nameCopy{static_cast<std::string>(entity->d_name)};
                 if (maskCopy != "") {
                     if (!caseSensitive) {
                         std::transform(maskCopy.begin(), maskCopy.end(), maskCopy.begin(), ::tolower);
                         std::transform(nameCopy.begin(), nameCopy.end(), nameCopy.begin(), ::tolower);
                     }
                     if (nameCopy.find(maskCopy) != std::string::npos) {
                         returnVector.emplace_back(entity->d_name);
                     }
                 } else { 
                     returnVector.emplace_back(entity->d_name);
                 }
             }
         }
         closedir (targetDirectory);
     } else {
         return std::vector<std::string>{};
     }
     return returnVector;
 }
Exemple #3
0
bool BSA::extractAll(const std::string& outputDirName, uint32_t& extractedFileCount)
{
  extractedFileCount = 0;
  if (!hasAllStructureData())
  {
    std::cout << "BSA::extractAll: Error: not all structure data is present "
              << "to properly fulfill the requested operation!\n";
    return false;
  }

  //check for output directory
  if (!directoryExists(outputDirName))
  {
    if (!createDirectoryRecursive(outputDirName))
    {
      std::cout << "BSA::extractAll: Error: Could not create destination directory \""
                << outputDirName << "\".\n";
      return false;
    }
  }

  uint32_t i, j;
  for (i=0; i<m_FolderBlocks.size(); ++i)
  {
    //create output directory, if necessary
    if (!directoryExists(outputDirName+MWTP::pathDelimiter+m_FolderBlocks[i].folderName))
    {
      if (!createDirectoryRecursive(outputDirName+MWTP::pathDelimiter+m_FolderBlocks[i].folderName))
      {
        std::cout << "BSA::extractAll: Error: Could not create destination subdirectory \""
                  << outputDirName+MWTP::pathDelimiter+m_FolderBlocks[i].folderName << "\".\n";
        return false;
      }
    }
    //now extract each file in that directory
    for (j=0; j<m_FolderBlocks[i].files.size(); ++j)
    {
      if (!extractFile(i, j, outputDirName+MWTP::pathDelimiter+m_FolderBlocks[i].folderName
           +MWTP::pathDelimiter+m_FolderBlocks[i].files[j].fileName))
      {
        std::cout << "BSA::extractAll: Error: Could not extract file \""
                  <<m_FolderBlocks[i].folderName+MWTP::pathDelimiter
                    +m_FolderBlocks[i].files[j].fileName<< "\".\n";
        return false;
      }//if
      ++extractedFileCount;
    }//for j
  }//for i

  return true;
}
Exemple #4
0
void Manga::download(unsigned int chapter)
{
	unsigned int i(1);
	std::list<Chapter>::iterator it(m_chapters.begin());
	while (i < chapter)
	{
		++i;
		++it;
		if (it == m_chapters.end())
		{
			std::cerr<<"Chapter "<<chapter<<" doesn't exist for "<<m_name<<"\n";
			return;
		}
	}
	
	
	char chapter_dir[300];
	sprintf(chapter_dir, "%s %u", m_name.c_str(), chapter);
	
	if (!testing)
	{
		if (!directoryExists("mangas/" + m_name + "/" + chapter_dir))
			createDirectory("mangas/" + m_name + "/" + chapter_dir);
		it->setDir("mangas/" + m_name + "/" + chapter_dir + "/");
	}
	
	
	it->setChapter(chapter);
	it->thDownload();
	
}
Exemple #5
0
bool CFileSystem::setWritePath(const std::string& path)
{
	if (!path.empty()) {
		if(!directoryExists(path)) {
			LOG_ERROR("filesystem-writepath doesn't exist: %s", path.c_str());
			return false;
		}
		springdir=path;
	} else {
#ifndef WIN32
		char* buf;
		buf=getenv("HOME");
		if (buf!=NULL) {
			springdir=buf;
			springdir.append("/.spring");
		} else { //no home: use cwd
			LOG_INFO("HOME isn't set, using CWD./spring");
			springdir=".spring";
		}
#else
		TCHAR pathMyDocs[MAX_PATH];
		SHGetFolderPath( NULL, CSIDL_PERSONAL, NULL, SHGFP_TYPE_CURRENT, pathMyDocs);
		springdir=pathMyDocs;
		springdir.append("\\My Games\\Spring");
#endif
	}
	LOG_INFO("Using filesystem-writepath: %s", springdir.c_str());
	return true;

}
inline bool makeDirectory(const std::string& path)
{
    if(directoryExists(path))
        return true;

    return (CreateDirectory(path.c_str(),NULL) == TRUE);
}
Exemple #7
0
STDMETHODIMP GuestSessionWrap::DirectoryExists(IN_BSTR aPath,
                                               BOOL *aExists)
{
    LogRelFlow(("{%p} %s:enter aPath=%ls aExists=%p\n", this, "GuestSession::directoryExists", aPath, aExists));

    VirtualBoxBase::clearError();

    HRESULT hrc;

    try
    {
        CheckComArgOutPointerValidThrow(aExists);

        AutoCaller autoCaller(this);
        if (FAILED(autoCaller.rc()))
            throw autoCaller.rc();

        hrc = directoryExists(BSTRInConverter(aPath).str(),
                              aExists);
    }
    catch (HRESULT hrc2)
    {
        hrc = hrc2;
    }
    catch (...)
    {
        hrc = VirtualBoxBase::handleUnexpectedExceptions(this, RT_SRC_POS);
    }

    LogRelFlow(("{%p} %s: leave aExists=%RTbool hrc=%Rhrc\n", this, "GuestSession::directoryExists", *aExists, hrc));
    return hrc;
}
Exemple #8
0
//&---------------------------------------------------------------------*
//&      Method  getSettingsFilePath
//&---------------------------------------------------------------------*
//
//----------------------------------------------------------------------*
std::string FileAccess::getSettingsFilePath() {
    std::string filePath = "";
    std::string homePath = getHomePath();
    if (homePath != "") {
        std::string moonPath = homePath + "/.moonfireflyGames";
        if (directoryExists(moonPath)) {
            filePath = moonPath + "/blokade.dat";
        }
        else {
			#if defined( BLOKADE_PLATFORM_OSX )
				if (mkdir(moonPath.c_str(), S_IRWXU | S_IRWXG) == 0) {
					filePath = moonPath + "/blokade.dat";
				}
            #elif defined( BLOKADE_PLATFORM_WINDOWS )
				if (CreateDirectory(moonPath.c_str(), NULL) ||
					ERROR_ALREADY_EXISTS == GetLastError()) {
					filePath = moonPath + "/blockade.dat";
				}
            #elif defined( BLOKADE_PLATFORM_LINUX )
				if (mkdir(moonPath.c_str(), S_IRWXU | S_IRWXG) == 0) {
					filePath = moonPath + "/blokade.dat";
				}
            #endif
        }
    }
    return filePath;
}
bool urdf_traverser::helpers::makeDirectoryIfNeeded(const char * dPath)
{
    if (directoryExists(dPath)) return true;
    try
    {
        boost::filesystem::path dir(dPath);
        boost::filesystem::path buildPath;

        for (boost::filesystem::path::iterator it(dir.begin()), it_end(dir.end()); it != it_end; ++it)
        {
            buildPath /= *it;
            //std::cout << buildPath << std::endl;

            if (!boost::filesystem::exists(buildPath) &&
                    !boost::filesystem::create_directory(buildPath))
            {
                ROS_ERROR_STREAM("Could not create directory " << buildPath);
                return false;
            }
        }
    }
    catch (const boost::filesystem::filesystem_error& ex)
    {
        ROS_ERROR_STREAM(ex.what());
        return false;
    }
    return true;
}
Exemple #10
0
UString LinuxEnvironment::getFolderFromFilePath(UString filepath)
{
	if (directoryExists(filepath)) // indirect check if this is already a valid directory (and not a file)
		return filepath;
	else
		return UString(dirname((char*)filepath.toUtf8()));
}
Exemple #11
0
bool CFileSystem::createSubdirs (const std::string& path) const
{
	std::string tmp=path;
	if (path[path.length()]!=PATH_DELIMITER) {
		tmp=tmp.substr(0,tmp.rfind(PATH_DELIMITER));
	}
	for (unsigned int i=2; i<tmp.size(); i++) {
		char c=tmp.at(i);
#ifdef WIN32
		if ((i==2) && (c == '\\'))
			continue;
#endif
		if (c==PATH_DELIMITER) {
			const std::string tocreate=tmp.substr(0,i);
			if (!fileSystem->directoryExists(tocreate)) {
				if (MKDIR(tmp.substr(0,i).c_str())!=0)
					return false;
			}
		}
	}

	if ((!directoryExists(tmp)) && (MKDIR(tmp.c_str()))!=0)
		return false;
	return true;
}
Exemple #12
0
/* 
 * Removes a directory.
 */
static int cs1550_rmdir(const char *path)
{
	char directory[strlen(path)];
	char filename[strlen(path)];
	char extension[strlen(path)];
	memset(&directory, 0, strlen(path));
	memset(&filename, 0, strlen(path));
	memset(&extension, 0, strlen(path));		
	int ret = sscanf(path, "/%[^/]/%[^.].%s", directory, filename, extension);
	
	if (ret == 1)															//It is actually a directory that we are removing
	{	
		FILE *temp = fopen(".tempDirectories", "a");						//Create a temp file to store everything but the dir we are removing
		cs1550_directory_entry *removeDir = directoryExists(path);			//Get that directory entry
		
		if (removeDir != NULL)												//The directory actually exists
		{
			if (removeDir->nFiles != 0)										//The directory is not empty
			{
				free(removeDir);
				fclose(temp);
				return -ENOTEMPTY;
			}
			cs1550_directory_entry tempEntry;								//Temp directory enrty
			memset(&tempEntry, 0, sizeof(cs1550_directory_entry));			//Set the memory to 0
			
			FILE *directories = NULL;
			directories = fopen(".directories", "r");
			
			if (directories != NULL)										//The directories file should always exist here because we found an entry to get to this point
			{
				while (fread(&tempEntry, sizeof(cs1550_directory_entry), 1, directories) == 1)
				{				
					if (strcmp(tempEntry.dname, removeDir->dname) != 0)		//If the one we are removing and the one we are looking at arent the same, write it
					{
						fwrite(&tempEntry, sizeof(cs1550_directory_entry), 1, temp);
					}
					memset(&tempEntry, 0, sizeof(cs1550_directory_entry));	//Reset memory
				}
				fclose(directories);
			}
			
			fclose(temp);
			system("cp .tempDirectories .directories");						//Copy temp over directories
			system("rm .tempDirectories");									//Remove temp
			free(removeDir);												//Space was allocated for this in directoryExists()
		}
		else																//Directory doesnt exist
		{			
			return -ENOENT;
		}
	}
	else if (ret > 1)														//Not a directory
	{
		return -ENOTDIR;
	}
	
    return 0;	//Success
}
Exemple #13
0
	bool File::directoryCreate( Path const & p_path, FlagCombination< CreateMode > const & p_flags )
	{
		Path path = p_path.getPath();

		if ( !path.empty() && !directoryExists( path ) )
		{
			directoryCreate( path, p_flags );
		}

		mode_t mode = 0;

		if ( checkFlag( p_flags, CreateMode::eUserRead ) )
		{
			mode |= S_IRUSR;
		}

		if ( checkFlag( p_flags, CreateMode::eUserWrite ) )
		{
			mode |= S_IWUSR;
		}

		if ( checkFlag( p_flags, CreateMode::eUserExec ) )
		{
			mode |= S_IXUSR;
		}

		if ( checkFlag( p_flags, CreateMode::eGroupRead ) )
		{
			mode |= S_IRGRP;
		}

		if ( checkFlag( p_flags, CreateMode::eGroupWrite ) )
		{
			mode |= S_IWGRP;
		}

		if ( checkFlag( p_flags, CreateMode::eGroupExec ) )
		{
			mode |= S_IXGRP;
		}

		if ( checkFlag( p_flags, CreateMode::eOthersRead ) )
		{
			mode |= S_IROTH;
		}

		if ( checkFlag( p_flags, CreateMode::eOthersWrite ) )
		{
			mode |= S_IWOTH;
		}

		if ( checkFlag( p_flags, CreateMode::eOthersExec ) )
		{
			mode |= S_IXOTH;
		}

		return mkdir( string::stringCast< char >( p_path ).c_str(), mode ) == 0;
	}
Exemple #14
0
static void CreateStateName(int nSlot)
{
	// create dir if dir doesn't exist
	if (!directoryExists(getMiscPath(PATH_SAVESTATE))) {
		CreateDirectory(getMiscPath(PATH_SAVESTATE), NULL);
	}

	_stprintf(szChoice, _T("%s%s slot %02x.fs"), getMiscPath(PATH_SAVESTATE), BurnDrvGetText(DRV_NAME), nSlot);
}
Exemple #15
0
/**
 * Creates directory recursively. Also access rights can be omitted. Defaults are 700 in unix.
 *
 * @param path full path of the directory created.
 * @param mode directory access rights, optional parameter, default value 0700 (owner: rwx, group: ---, others: ---)
 * @throws IOException exception is thrown if the directory creation failed.
 */
void digidoc::util::File::createDirectory(const std::string& path) throw(IOException)
{
    if(path.empty())
    {
        THROW_IOEXCEPTION("Can not create directory with no name.");
    }

    if(directoryExists(path))
    {
        return;
    }

    std::string parentDir(path);
    if(parentDir[parentDir.size() - 1] == '/' || parentDir[parentDir.size() - 1] == '\\')
    {
        parentDir = parentDir.substr(0, parentDir.size() - 1);
    }
    parentDir = parentDir.substr(0, parentDir.find_last_of("/\\"));

    if(!directoryExists(parentDir))
    {
        createDirectory(parentDir);
    }

    f_string _path = encodeName(path);
#ifdef _WIN32
    int result = _wmkdir(_path.c_str());
    if ( result )
        DEBUG("Creating directory '%s' failed with errno = %d", _path.c_str(), errno);
    else
        DEBUG("Created directory '%s'", _path.c_str());
#else
    umask(0);
    int result = mkdir(_path.c_str(), 0700);
    DEBUG("Created directory '%s' with result = %d", _path.c_str(), result);
#endif

    if(result || !directoryExists(path))
    {
        THROW_IOEXCEPTION("Failed to create directory '%s'", path.c_str());
    }
}
Exemple #16
0
/**
 * Tries to delete all temporary files and directories whose names were handled out with tempFileName, tempDirectory and createTempDirectory.
 * The deletion of directories is recursive.
 */
void digidoc::util::File::deleteTempFiles() throw(IOException)
{
    while (!tempFiles.empty())
    {
        if ( directoryExists(tempFiles.top()) )
            removeDirectoryRecursively(tempFiles.top());
        else
            removeFile(tempFiles.top());
        tempFiles.pop();
    }
}
Exemple #17
0
		std::wstring getFileName(std::wstring pathname, std::wstring filename) {
			if (file_.empty()) {
				std::wstring path = getFolder() + _T("\\") + pathname;
				if (!directoryExists(path)) {
					if (_wmkdir(path.c_str()) != 0)
						return _T("");
				}
				file_ = path + _T("\\") + filename;
			}
			return file_;
		}
//==============================================================================
void createDirectory(const CString& dir)
{
	if(directoryExists(dir))
	{
		return;
	}

	if(mkdir(dir.get(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH))
	{
		throw ANKI_EXCEPTION("%s : %s", strerror(errno), dir.get());
	}
}
Exemple #19
0
 bool directoryExists(const std::string &directoryToCheck)
 { 
     struct stat info;
     if(stat(directoryToCheck.c_str(), &info) != 0) {
         return false;
     } else if(info.st_mode & S_IFDIR)  { 
         return true;
     } else {
         return false;
     }
     return directoryExists(directoryToCheck.c_str());
 }
std::string FileUtils::systemTemporaryDir()
{
#ifdef _WIN32
    const wchar_t *value;

    if ((value = _wgetenv(L"TMP")) && directoryExists(value)) {
        return utf8::utf16ToUtf8(value);
    }
    if ((value = _wgetenv(L"TEMP")) && directoryExists(value)) {
        return utf8::utf16ToUtf8(value);
    }
    if ((value = _wgetenv(L"LOCALAPPDATA"))) {
        std::wstring path(value);
        path += L"\\Temp";
        if (directoryExists(path.c_str())) {
            return utf8::utf16ToUtf8(path);
        }
    }
    if ((value = _wgetenv(L"USERPROFILE"))) {
        std::wstring path(value);
        path += L"\\Temp";
        if (directoryExists(path.c_str())) {
            return utf8::utf16ToUtf8(path);
        }
    }

    return std::string();
#else
    const char *value;

    if ((value = getenv("TMPDIR")) && directoryExists(value)) {
        return value;
    }
    if ((value = getenv("TMP")) && directoryExists(value)) {
        return value;
    }
    if ((value = getenv("TEMP")) && directoryExists(value)) {
        return value;
    }
    if ((value = getenv("TEMPDIR")) && directoryExists(value)) {
        return value;
    }

    return "/tmp";
#endif
}
Exemple #21
0
 bool findFilesRecursive( std::string const& extension, std::string const& path, std::vector<std::string> & results )
 {
   bool found = false;
   boost::filesystem::path searchPath( path );
   DP_ASSERT( directoryExists( searchPath.string() ) );
   for ( boost::filesystem::recursive_directory_iterator dirIt( searchPath ) ; dirIt != boost::filesystem::recursive_directory_iterator() ; ++dirIt )
   {
     if ( _stricmp( dirIt->path().extension().string().c_str(), extension.c_str() ) == 0 )
     {
       results.push_back( dirIt->path().string() );
       found = true;
     }
   }
   return( found );
 }
extern "C" UINT __stdcall  DirectoryExists(MSIHANDLE hInstall) {
   bool found;

   ::hInstall = hInstall;

   char path[MAX_PATH];
   DWORD filePathLength = MAX_PATH;

   MsiGetProperty (hInstall, "MYCA_PATH", path, &filePathLength);

   // Attempt to get the subdir attributes
   found = directoryExists(path);
   MsiSetProperty (hInstall, "MYCA_EXISTS", found?"1":"0");

   printLog("DirectoryExists(%s) => %s\n", path, found?"Found":"Not Found");
   return ERROR_SUCCESS;
}
Exemple #23
0
void setConfigKey(char *value) {
    if (dir_key != NULL) free(dir_key);         /* free memory */

	if (value == NULL) {
		dir_key = malloc (strlen(dir_config)+1+strlen("key")+1);
		sprintf(dir_key, "%s/key", dir_config);
	} else {
		dir_key = malloc (strlen(value)+1);
		strcpy(dir_key, value);
	}
	
	mkdir(dir_key, 0755);
	if (!directoryExists(dir_key)) {
		printf ( "ERROR: Directory (%s) doesn't exists.\n", dir_key );
		exit(EXIT_FAILURE);
	}
	printf ( "KEY: %s\n", dir_key );
}
Exemple #24
0
bool BSA::extractFolder(const uint32_t folderIndex, const std::string& outputDirName, uint32_t& extractedFileCount)
{
  extractedFileCount = 0;
  if (!hasAllStructureData())
  {
    std::cout << "BSA::extractFolder: Error: not all structure data is present "
              << "to properly fulfill the requested operation!\n";
    return false;
  }

  if ((folderIndex==cIndexNotFound) or (folderIndex>=m_FolderBlocks.size()))
  {
    std::cout << "BSA::extractFolder: Error: invalid folder index!\n";
    return false;
  }

  //check for output directory
  if (!directoryExists(outputDirName))
  {
    if (!createDirectoryRecursive(outputDirName))
    {
      std::cout << "BSA::extractFolder: Error: Could not create destination directory \""
                << outputDirName << "\".\n";
      return false;
    }
  }

  uint32_t file_index;
  //now extract each file in that directory
  for (file_index=0; file_index<m_FolderBlocks[folderIndex].files.size(); ++file_index)
  {
    if (!extractFile(folderIndex, file_index, outputDirName+MWTP::pathDelimiter
         +m_FolderBlocks[folderIndex].files[file_index].fileName))
    {
      std::cout << "BSA::extractFolder: Error: Could not extract file \""
                << m_FolderBlocks[folderIndex].folderName+MWTP::pathDelimiter
                  +m_FolderBlocks[folderIndex].files[file_index].fileName<< "\".\n";
      return false;
    }//if
    ++extractedFileCount;
  }//for file_index

  return true;
}
Exemple #25
0
void setConfigRestore(char *value) {
    if (dir_restore != NULL) free(dir_restore); /* free memory */

	if (value == NULL) {
		dir_restore = malloc (strlen(dir_config)+1+strlen("restore")+1);
		sprintf(dir_restore, "%s/restore", dir_config);
	} else {
		dir_restore = malloc (strlen(value)+1);
		strcpy(dir_restore, value);
	}

	mkdir(dir_restore, 0755);
	if (!directoryExists(dir_restore)) {
		printf ( "ERROR: Directory (%s) doesn't exists.\n", dir_restore );
		exit(EXIT_FAILURE);
	}

	printf ( "RESTORE: %s\n", dir_restore );
}
Exemple #26
0
int main(void){
  char *home=malloc(20);
  char *temp=malloc(100);
  strcpy(home,getenv("HOME"));
  system("sudo apt-get install $(grep -vE \"^\\s*#\" \"$HOME/Documents/package-list\"  | tr \"\n\n\"5 \" \")");
  strcpy(temp,home);

  strcat(temp,"/.fonts");
  puts("Does the ~/.fonts/ directory exist?");
  if(mkdir(temp,0755)==0){
    puts("~/.fonts/ was created because it did not exist.");
  }
  else{
    puts("~/.fonts/ does exist, which is why it will not be created.");
  }
  printf("\n");

  strcat(temp,"/ubuntu-fonts");
  puts("Does the ~/.fonts/ubuntu-fonts/ directory exist?");
  if(directoryExists(temp)){
    puts("It does, assuming ubuntu-fonts area already installed.");
  }
  else{
    puts("It does not, attempting to install ubuntu-fonts.");
    system("wget http://font.ubuntu.com/download/ubuntu-font-family-0.83.zip -O /tmp/u-fonts.zip&&7z x -o${HOME}/.fonts/ /tmp/u-fonts.zip&&mv $HOME/.fonts/ubuntu-font-family-0.83 $HOME/.fonts/ubuntu-fonts");
    puts("Done.");
  }
  printf("\n");

  puts("Does /usr/bin/node exist? (Assuming NodeJS is installed)");
  if(fileExists("/usr/bin/node")){
    puts("It does, not linking it from nodejs.");
  }
  else{
    puts("It does not, linking it from /usr/bin/nodejs");
    system("sudo ln -s /usr/bin/nodejs /usr/bin/node");
  }
  printf("\n");


}
Exemple #27
0
int CFileSystem::validatePool(const std::string& path)
{
	if(!directoryExists(path)) {
		LOG_ERROR("Pool directory doesn't exist: %s", path.c_str());
		return 0;
	}
	int res=0;
	std::list <std::string>dirs;
	dirs.push_back(path);
	int maxdirs=257; //FIXME: unknown dirs in pool will break bar
	int finished=0;
	IHash* md5=new HashMD5();
	while(!dirs.empty()) {
		struct dirent* dentry;
		DIR* d;
		const std::string dir=dirs.front();
		dirs.pop_front();
		d=opendir(dir.c_str());
		while ( (dentry=readdir(d))!=NULL) {
			LOG_PROGRESS(finished, maxdirs);
			std::string absname=dir;
			absname += PATH_DELIMITER;
			absname += dentry->d_name;
			if (dentry->d_name[0]!='.') { //don't check hidden files / . / ..
#ifndef WIN32
				if ((dentry->d_type & DT_DIR)!=0) { //directory
#else
				struct stat sb;
				stat(absname.c_str(), &sb);
				if((sb.st_mode & S_IFDIR)!=0) {
#endif
					dirs.push_back(absname);
				} else {
					FileData filedata=FileData();
					int len=absname.length();
					if (len<36) { //file length has at least to be <md5[0]><md5[1]>/<md5[2-30]>.gz
						LOG_ERROR("Invalid file: %s", absname.c_str());
					} else {
						std::string md5str="";
						md5str.push_back(absname.at(len-36)); //get md5 from path + filename
						md5str.push_back(absname.at(len-35));
						md5str.append(absname.substr(len-33, 30));
						md5->Set(md5str);
						for(unsigned i=0; i<16; i++) {
							filedata.md5[i]=md5->get(i);
						}

						if (!fileIsValid(&filedata, absname)) { //check if md5 in filename is the same as in filename
							LOG_ERROR("Invalid File in pool: %s",absname.c_str());
						} else {
							res++;
						}
					}
				}
			}
		}
		finished++;
		closedir(d);
	}
	delete md5;
	LOG_PROGRESS(finished, maxdirs, true);
	LOG("");
	return res;
}

bool CFileSystem::isOlder(const std::string& filename, int secs)
{
	struct stat sb;
	if (stat(filename.c_str(),&sb)<0) {
		return true;
	}
	time_t t;
#ifdef WIN32
	SYSTEMTIME pTime;
	FILETIME pFTime;
	GetSystemTime(&pTime);
	SystemTimeToFileTime(&pTime, &pFTime);
	t =  FiletimeToTimestamp(pFTime);
#else
	time(&t);
#endif
	LOG_DEBUG("%s is %d seconds old, redownloading at %d",filename.c_str(), (int)(t - sb.st_ctime), secs);
	return (t<sb.st_ctime+secs);
}

bool CFileSystem::fileExists(const std::string& filename)
{
	struct stat buffer;
	return stat(filename.c_str(), &buffer) == 0;
}

bool CFileSystem::parseTorrent(const char* data, int size, IDownload* dl)
{
	struct be_node* node=be_decoden(data, size);
//#ifdef DEBUG
//	be_dump(node);
//#endif
	if(node==NULL) {
		LOG_ERROR("couldn't parse torrent");
		return false;
	}
	if (node->type!=BE_DICT) {
		LOG_ERROR("Error in torrent data");
		be_free(node);
		return false;
	}
	int i;
	struct be_node* infonode=NULL;
	for (i = 0; node->val.d[i].val; ++i) { //search for a dict with name info
		if ((node->type==BE_DICT) && (strcmp(node->val.d[i].key,"info")==0)) {
			infonode=node->val.d[i].val;
			break;
		}
	}
	if (infonode==NULL) {
		LOG_ERROR("couldn't find info node in be dict");
		be_free(node);
		return false;
	}
	for (i = 0; infonode->val.d[i].val; ++i) { //fetch needed data from dict and fill into dl
		struct be_node*datanode;
		datanode=infonode->val.d[i].val;
		switch(datanode->type) {
		case BE_STR: //current value is a string
			if ((strcmp("name",infonode->val.d[i].key)==0) && (dl->name.empty())) { //set filename if not already set
				dl->name=datanode->val.s;
			} else if (!strcmp("pieces", infonode->val.d[i].key)) { //hash sum of a piece
				const int count = be_str_len(datanode)/20; //one sha1 sum is 5 * 4 bytes long
				for (int i=0; i<count; i++) {
					struct IDownload::piece piece;
					const unsigned char* data=(unsigned char*)&datanode->val.s[i*20];
					piece.sha=new HashSHA1();
					if (!piece.sha->Set(data, 20)) {
						LOG_ERROR("Error setting sha1");
					}
					piece.state=IDownload::STATE_NONE;
					dl->pieces.push_back(piece);
				}
			}
			break;
		case BE_INT: //current value is a int
			if (strcmp("length",infonode->val.d[i].key)==0) { //filesize
				dl->size=datanode->val.i;
			} else if (!strcmp("piece length",infonode->val.d[i].key)) { //length of a piece
				dl->piecesize=datanode->val.i;
				LOG_DEBUG("dl->piecesize: %d", dl->piecesize);
			}
			break;
		default:
			break;
		}
	}
	LOG_DEBUG("Parsed torrent data: %s %d", dl->name.c_str(), dl->piecesize);
	be_free(node);
	return true;
}

bool CFileSystem::dumpSDP(const std::string& filename)
{
	std::list<FileData*> files;
	files.clear();
	if (!parseSdp(filename, files))
		return false;
	LOG_INFO("md5 (filename in pool)           crc32        size filename");
	std::list<FileData*>::iterator it;
	HashMD5 md5;
	for(it=files.begin(); it!=files.end(); ++it) {
		md5.Set((*it)->md5, sizeof((*it)->md5));
		LOG_INFO("%s %.8X %8d %s",md5.toString().c_str(), (*it)->crc32, (*it)->size, (*it)->name.c_str());
	}
	return true;
}
Exemple #28
0
static int
validateTestDir1_renamed(
    const char *parentDir,
    const char *dirName)
{
    int exitStatus = 0;
    char *dirpath = joinPaths(parentDir, dirName);
    if (0 == directoryExists(dirpath))
    {
        fprintf(stdout, "FOUND directory: '%s'\n", dirpath);

        /* check for files within directory */
        {
            char *path = joinPaths(dirpath, "file1.txt");
            if (0 == fileExists(path))
            {
                fprintf(stdout, "FOUND file: '%s'\n", path);
            }
            else
            {
                fprintf(stderr, "Unable to locate file '%s'\n", path);
                ++exitStatus;
            }
            free(path);
        }
            {
                char *path = joinPaths(dirpath, "file2.txt");
                if (0 == fileExists(path))
                {
                    fprintf(stdout, "FOUND file: '%s'\n", path);
                }
                else
                {
                    fprintf(stderr, "Unable to locate file '%s'\n", path);
                    ++exitStatus;
                }
                free(path);
            }

            /* check for subdirectory */
            {
                char *subdirPath = joinPaths(dirpath, "subdir");
                if (0 == directoryExists(subdirPath))
                {
                    fprintf(stdout, "FOUND directory: '%s'\n", subdirPath);

                    /* check for file in subdir */
                    {
                        char *path = joinPaths(subdirPath, "file3.txt");
                        if (0 == fileExists(path))
                        {
                            fprintf(stdout, "FOUND file: '%s'\n", path);
                        }
                        else
                        {
                            fprintf(stderr, "Unable to locate file '%s'\n", path);
                            ++exitStatus;
                        }
                        free(path);
                    }
                }
                else
                {
                    fprintf(stderr, "Unable to directory file '%s'\n", subdirPath);
                    ++exitStatus;
                }
                free(subdirPath);
            }
    }
    else
    {
        fprintf(stderr, "Unable to locate directory '%s'\n", dirpath);
        ++exitStatus;
    }
    free(dirpath);
    return exitStatus;
}
Exemple #29
0
int openproject (char *file)
{
	json_object		*prj = NULL;
	json_object		*srcDir = NULL;
	char			name[201] = {0};
	int				nSrcDirs = 0;
	int				loop = 0;
	const char		*folder;
	char			*srcPath = NULL;
	const char		*pPrjName = NULL;

	prj = json_object_from_file(file);
	if (!prj) {
		return -1;
	}

	loop = strlen(file);
	while (file[loop] != '\\') {
		loop--;
	}
	if (loop >=0 ) {
		file[loop] = '\0';
	}

	/* Check for project folder */
	if (!directoryExists(file)) {
		return -1;
	}

	pPrjName = json_object_get_string(json_object_object_get(prj, NAME));
	while (*pPrjName) {
		if (*pPrjName == '\\') {
			folder = pPrjName;
		}
		pPrjName++;
	}
	pPrjName = ++folder;
	folder = NULL;

	/* Get the source path */
	nSrcDirs = json_object_get_int(json_object_object_get(prj, NOFSRCDIRS));
	srcDir = json_object_object_get (prj, SRCDIRS);

	for (loop = 0; loop < 1 /*nSrcDirs*/; loop++) {
		folder = json_object_get_string(json_object_array_get_idx(srcDir, loop));
	}

	/* Check for source folder */
	if (!directoryExists(folder)) {
		return -1;
	}


	generateBatchFile(pPrjName, file, folder);
	buildCscope(file);

	sprintf(name, "%s\\%s.conf", file, pPrjName);

	myinit (name);

	json_object_put(prj);

	return 1;
}
int main(int numargs, char *args[]) {
	FILE *archiveFile;
	CLookToRead archiveStream;
	CSzArEx db;
	int res;
	
	
	if (numargs != 3) {
		return 1;
	}
	if ((archiveFile = fopen(args[1], "r")) == NULL) {
		return 2;
	}
	if (!directoryExists(args[2])) {
		return 4;		
	}
	
	int outPathLen = strlen(args[2]);
	int maxPathLen = 5;
	int pathLen;
	char *outputPath;
	
	outputPath = malloc(outPathLen + maxPathLen + 1);
	memcpy(outputPath, args[2], outPathLen);
	if (outputPath[outPathLen - 1] != '/') {
		outputPath[outPathLen] = '/';
		outPathLen++;
		maxPathLen--; 
	}
	
	
	archiveStream.file = &archiveFile;
	LookToRead_Init(&archiveStream);
	
	CrcGenerateTable();
	
	SzArEx_Init(&db);
	res = SzArEx_Open(&db, &archiveStream);
	if (res == SZ_OK) {
		UInt32 i;
		
		UInt32 blockIndex;
		Byte *outBuffer = 0;
		size_t outBufferSize;
		
		for (i = 0; i < db.db.NumFiles; i++) {
			size_t offset;
			size_t outSizeProcessed;
			CSzFileItem *f = db.db.Files + i;
			
			pathLen = strlen(f->Name);
			if (pathLen > maxPathLen) {
				maxPathLen = pathLen * 2;
				outputPath = realloc(outputPath, outPathLen + maxPathLen + 1);
			}
			memcpy(outputPath + outPathLen, f->Name, pathLen + 1);
			
			mode_t fileMode;
			if (f->AttribDefined && f->Attrib & 0x8000) {
				fileMode = f->Attrib >> 16;
			} else {