示例#1
0
// mklink /D "C:\existingFolder\Link" "C:\Target"
// mklink /D "C:\existingFolder\Link\" "C:\Target\"
// The ending slash is optional. The parent directory of the link must exist.
bool BrainUtil::MakeLink(const CString& link, const CString& target, bool bIsDirectory/* = true*/)
{
    CString temLink = link;
    CString temTarget = target;

    // delete the last '\'
    WCHAR lastChar = temLink.GetAt(temLink.GetLength() - 1);
    if(lastChar == _T('\\'))
        temLink.Truncate(temLink.GetLength() - 1); 

    if(DoesFileorFolderExist(temLink))
    {
        // Delete the link
        // For links to directories: rmdir linkname
        // For links to files: del linkname
        CString tmpCmd;
        tmpCmd.Format(_T("rmdir \"%s\""), temLink.GetBuffer());
        RunSystemCommand(tmpCmd);

        if(DoesFileorFolderExist(temLink)) // If still exist it might be a file link
        {
            tmpCmd.Format(_T("del \"%s\""), temLink.GetBuffer());
            RunSystemCommand(tmpCmd);
        }

        if(DoesFileorFolderExist(temLink))// check again
        {
            DATA_ASSERT(false); 
            return false;
        }
    }
    else
    {
        CString folderFullName = GetParentFolderName(link);
        if(!DoesFileorFolderExist(folderFullName))
        {
            bool bRet = CreateFolder(folderFullName); // Create the parent directory tree.
            if(!bRet)
                return false;
        }
    }

    CString cmd;
    if(bIsDirectory)
        cmd.Format(_T("mklink /D \"%s\" \"%s\""), temLink.GetBuffer(), temTarget.GetBuffer());
    else
        cmd.Format(_T("mklink \"%s\" \"%s\""), temLink.GetBuffer(), temTarget.GetBuffer());

    int ret = _wsystem(cmd.GetBuffer());
    DATA_ASSERT(0 == ret);
    bool bSucc = DoesFileorFolderExist(link);
    return bSucc;
}
 // This tries to run mkdir with the -p argument, throwing an exception if it
 // could not.
 inline void FilePlaceholderManager::EnsureDirectoryExists(
                                            std::string const& directoryName )
 {
   std::stringstream commandBuilder;
   commandBuilder << "mkdir -p " << directoryName;
   RunSystemCommand( commandBuilder.str() );
 }
 // This deletes the file with the given name, throwing an exception if it
 // cannot.
 inline void FilePlaceholderManager::DeleteFile( std::string const& fileName )
 {
   std::stringstream commandBuilder;
   commandBuilder << "rm " << fileName;
   RunSystemCommand( commandBuilder.str() );
 }