Пример #1
0
BOOL
SearchForExecutableSingle (LPCTSTR pFileName, LPTSTR pFullName, LPTSTR pPathExt, LPTSTR pDirectory)
{
    TCHAR  szPathBuffer[CMDLINE_LENGTH], *pszPathEnd;
    LPTSTR s,f;
    /* initialize full name buffer */
    *pFullName = _T('\0');

    TRACE ("SearchForExecutableSingle: \'%s\' in dir: \'%s\'\n",
        debugstr_aw(pFileName), debugstr_aw(pDirectory));

    pszPathEnd = szPathBuffer;
    if (pDirectory != NULL)
    {
        _tcscpy(szPathBuffer, pDirectory);
        pszPathEnd += _tcslen(pszPathEnd);
        *pszPathEnd++ = _T('\\');
    }
    _tcscpy(pszPathEnd, pFileName);
    pszPathEnd += _tcslen(pszPathEnd);

    if (IsExistingFile (szPathBuffer))
    {
        TRACE ("Found: \'%s\'\n", debugstr_aw(szPathBuffer));
        _tcscpy (pFullName, szPathBuffer);
        return TRUE;
    }

    s = pPathExt;
    while (s && *s)
    {
        f = _tcschr (s, _T(';'));

        if (f)
        {
            _tcsncpy (pszPathEnd, s, (size_t)(f-s));
            pszPathEnd[f-s] = _T('\0');
            s = f + 1;
        }
        else
        {
            _tcscpy (pszPathEnd, s);
            s = NULL;
        }

        if (IsExistingFile (szPathBuffer))
        {
            TRACE ("Found: \'%s\'\n", debugstr_aw(szPathBuffer));
            _tcscpy (pFullName, szPathBuffer);
            return TRUE;
        }
    }
    return FALSE;
}
Пример #2
0
/* makes the replace */
INT replace(TCHAR source[MAX_PATH], TCHAR dest[MAX_PATH], DWORD dwFlags, BOOL *doMore)
{
    TCHAR d[MAX_PATH];
    TCHAR s[MAX_PATH];
    HANDLE hFileSrc, hFileDest;
    DWORD  dwAttrib, dwRead, dwWritten;
    LPBYTE buffer;
    BOOL   bEof = FALSE;
    FILETIME srcCreationTime, destCreationTime, srcLastAccessTime, destLastAccessTime;
    FILETIME srcLastWriteTime, destLastWriteTime;
    GetPathCase(source, s);
    GetPathCase(dest, d);
    s[0] = _totupper(s[0]);
    d[0] = _totupper(d[0]);
    // ConOutPrintf(_T("old-src:  %s\n"), s);
    // ConOutPrintf(_T("old-dest: %s\n"), d);
    // ConOutPrintf(_T("src:  %s\n"), source);
    // ConOutPrintf(_T("dest: %s\n"), dest);

    /* Open up the sourcefile */
    hFileSrc = CreateFile (source, GENERIC_READ, FILE_SHARE_READ,NULL, OPEN_EXISTING, 0, NULL);
    if (hFileSrc == INVALID_HANDLE_VALUE)
    {
        ConOutResPrintf(STRING_COPY_ERROR1, source);
        return 0;
    }

    /*
     * Get the time from source file to be used in the comparison
     * with dest time if update switch is set.
     */
    GetFileTime (hFileSrc, &srcCreationTime, &srcLastAccessTime, &srcLastWriteTime);

    /*
     * Retrieve the source attributes so that they later on
     * can be inserted in to the destination.
     */
    dwAttrib = GetFileAttributes (source);

    if (IsExistingFile (dest))
    {
        /*
         * Resets the attributes to avoid probles with read only files,
         * checks for read only has been made earlier.
         */
        SetFileAttributes(dest,FILE_ATTRIBUTE_NORMAL);
        /*
         * Is the update flas set? The time has to be controled so that
         * only older files are replaced.
         */
        if (dwFlags & REPLACE_UPDATE)
        {
            /* Read destination time */
            hFileDest = CreateFile(dest, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING,
                0, NULL);

            if (hFileSrc == INVALID_HANDLE_VALUE)
            {
                ConOutResPrintf(STRING_COPY_ERROR1, dest);
                return 0;
            }

            /* Compare time */
            GetFileTime (hFileDest, &destCreationTime, &destLastAccessTime, &destLastWriteTime);
            if (!((srcLastWriteTime.dwHighDateTime > destLastWriteTime.dwHighDateTime) ||
                    (srcLastWriteTime.dwHighDateTime == destLastWriteTime.dwHighDateTime &&
                     srcLastWriteTime.dwLowDateTime > destLastWriteTime.dwLowDateTime)))
            {
                CloseHandle (hFileSrc);
                CloseHandle (hFileDest);
                return 0;
            }
            CloseHandle (hFileDest);
        }
        /* Delete the old file */
        DeleteFile (dest);
    }

    /* Check confirm flag, and take appropriate action */
    if (dwFlags & REPLACE_CONFIRM)
    {
        /* Output depending on add flag */
        if (dwFlags & REPLACE_ADD)
            ConOutResPrintf(STRING_REPLACE_HELP9, dest);
        else
            ConOutResPrintf(STRING_REPLACE_HELP10, dest);
        if ( !FilePromptYNA (0))
            return 0;
    }

    /* Output depending on add flag */
    if (dwFlags & REPLACE_ADD)
        ConOutResPrintf(STRING_REPLACE_HELP11, dest);
    else
        ConOutResPrintf(STRING_REPLACE_HELP5, dest);

    /* Make sure source and destination is not the same */
    if (!_tcscmp(s, d))
    {
        ConOutResPaging(TRUE, STRING_REPLACE_ERROR7);
        CloseHandle (hFileSrc);
        *doMore = FALSE;
        return 0;
    }

    /* Open destination file to write to */
    hFileDest = CreateFile (dest, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
    if (hFileDest == INVALID_HANDLE_VALUE)
    {
        CloseHandle (hFileSrc);
        ConOutResPaging(TRUE, STRING_REPLACE_ERROR7);
        *doMore = FALSE;
        return 0;
    }

    /* Get buffer for the copy process */
    buffer = VirtualAlloc(NULL, BUFF_SIZE, MEM_COMMIT, PAGE_READWRITE);
    if (buffer == NULL)
    {
        CloseHandle (hFileDest);
        CloseHandle (hFileSrc);
        ConOutResPaging(TRUE, STRING_ERROR_OUT_OF_MEMORY);
        return 0;
    }

    /* Put attribute and time to the new destination file */
    SetFileAttributes (dest, dwAttrib);
    SetFileTime (hFileDest, &srcCreationTime, &srcLastAccessTime, &srcLastWriteTime);
    do
    {
        /* Read data from source */
        ReadFile (hFileSrc, buffer, BUFF_SIZE, &dwRead, NULL);

        /* Done? */
        if (dwRead == 0)
            break;

        /* Write to destination file */
        WriteFile (hFileDest, buffer, dwRead, &dwWritten, NULL);

        /* Done! or ctrl break! */
        if (dwWritten != dwRead || CheckCtrlBreak(BREAK_INPUT))
        {
            ConOutResPuts(STRING_COPY_ERROR3);
            VirtualFree (buffer, 0, MEM_RELEASE);
            CloseHandle (hFileDest);
            CloseHandle (hFileSrc);
            nErrorLevel = 1;
            return 0;
        }
    }
    while (!bEof);

    /* Return memory and close files */
    VirtualFree (buffer, 0, MEM_RELEASE);
    CloseHandle (hFileDest);
    CloseHandle (hFileSrc);

    /* Return one file replaced */
    return 1;
}
Пример #3
0
INT cmd_replace (LPTSTR param)
{
    LPTSTR *arg;
    INT argc, i,filesReplaced = 0, nFiles, srcIndex = -1, destIndex = -1;
    DWORD dwFlags = 0;
    TCHAR szDestPath[MAX_PATH], szSrcPath[MAX_PATH], tmpSrcPath[MAX_PATH];
    BOOL doMore = TRUE;

    /* Help wanted? */
    if (!_tcsncmp (param, _T("/?"), 2))
    {
        ConOutResPaging(TRUE,STRING_REPLACE_HELP1);
        return 0;
    }

    /* Divide the argument in to an array of c-strings */
    arg = split (param, &argc, FALSE, FALSE);
    nFiles = argc;

    /* Read options */
    for (i = 0; i < argc; i++)
    {
        if (arg[i][0] == _T('/'))
        {
            if (_tcslen(arg[i]) == 2)
            {
                switch (_totupper(arg[i][1]))
                {
                case _T('A'):
                    dwFlags |= REPLACE_ADD;
                    break;
                case _T('P'):
                    dwFlags |= REPLACE_CONFIRM;
                    break;
                case _T('R'):
                    dwFlags |= REPLACE_READ_ONLY;
                    break;
                case _T('S'):
                    dwFlags |= REPLACE_SUBDIR;
                    break;
                case _T('W'):
                    dwFlags |= REPLACE_DISK;
                    break;
                case _T('U'):
                    dwFlags |= REPLACE_UPDATE;
                    break;
                default:
                    invalid_switch(arg[i]);
                    return 0;
                }
            }
            else
            {
                invalid_switch(arg[i]);
                freep(arg);
                return 0;
            }
            nFiles--;
        }
        else
        {
            if (srcIndex == -1)
            {
                srcIndex = i;
            }
            else if (destIndex == -1)
            {
                destIndex = i;
            }
            else
            {
                invalid_switch(arg[i]);
                freep(arg);
                return 0;
            }
        }
    }

    /* See so that at least source is there */
    if (nFiles < 1)
    {
        ConOutResPaging(TRUE,STRING_REPLACE_HELP2);
        ConOutResPaging(TRUE,STRING_REPLACE_HELP3);
        freep(arg);
        return 1;
    }
    /* Check so that not both update and add switch is added and subdir */
    if ((dwFlags & REPLACE_UPDATE || dwFlags & REPLACE_SUBDIR) && (dwFlags & REPLACE_ADD))
    {
        ConOutResPaging(TRUE,STRING_REPLACE_ERROR4);
        ConOutResPaging(TRUE,STRING_REPLACE_HELP7);
        freep(arg);
        return 1;
    }

    /* If we have a destination get the full path */
    if (destIndex != -1)
    {
        if (_tcslen(arg[destIndex]) == 2 && arg[destIndex][1] == ':')
            GetRootPath(arg[destIndex],szDestPath,MAX_PATH);
        else
        {
            /* Check for wildcards in destination directory */
            if (_tcschr (arg[destIndex], _T('*')) != NULL ||
                _tcschr (arg[destIndex], _T('?')) != NULL)
            {
                ConOutResPrintf(STRING_REPLACE_ERROR2,arg[destIndex]);
                ConOutResPaging(TRUE,STRING_REPLACE_HELP3);
                freep(arg);
                return 1;
            }
            getPath(szDestPath, arg[destIndex]);
            /* Make sure that destination exists */
            if (!IsExistingDirectory(szDestPath))
            {
                ConOutResPrintf(STRING_REPLACE_ERROR2, szDestPath);
                ConOutResPaging(TRUE,STRING_REPLACE_HELP3);
                freep(arg);
                return 1;
            }
        }
    }
    else
    {
        /* Dest is current dir */
        GetCurrentDirectory(MAX_PATH,szDestPath);
    }

    /* Get the full source path */
    if (!(_tcslen(arg[srcIndex]) == 2 && arg[srcIndex][1] == ':'))
        getPath(szSrcPath, arg[srcIndex]);
    else
        _tcscpy(szSrcPath,arg[srcIndex]);

    /* Source does not have wildcards */
    if (_tcschr (arg[srcIndex], _T('*')) == NULL &&
        _tcschr (arg[srcIndex], _T('?')) == NULL)
    {
        /* Check so that source is not a directory, because that is not allowed */
        if (IsExistingDirectory(szSrcPath))
        {
            ConOutResPrintf(STRING_REPLACE_ERROR6, szSrcPath);
            ConOutResPaging(TRUE,STRING_REPLACE_HELP3);
            freep(arg);
            return 1;
        }
        /* Check if the file exists */
        if (!IsExistingFile(szSrcPath))
        {
            ConOutResPaging(TRUE,STRING_REPLACE_HELP3);
            freep(arg);
            return 1;
        }
    }
    /* /w switch is set so wait for any key to be pressed */
    if (dwFlags & REPLACE_DISK)
    {
        msg_pause();
        cgetchar();
    }

    /* Add an extra \ to the destination path if needed */
    if (szDestPath[_tcslen(szDestPath) -  1] != _T('\\'))
        _tcscat(szDestPath, _T("\\"));

    /* Save source path */
    _tcscpy(tmpSrcPath,szSrcPath);
    /* Replace in dest dir */
    filesReplaced += recReplace(dwFlags, tmpSrcPath, szDestPath, &doMore);
    /* If subdir switch is set replace in the subdirs to */
    if (dwFlags & REPLACE_SUBDIR && doMore)
    {
        filesReplaced += recFindSubDirs(dwFlags, szSrcPath,  szDestPath, &doMore);
    }

    /* If source == dest write no more */
    if (filesReplaced != -1)
    {
        /* No files replaced */
        if (filesReplaced==0)
        {
            /* Add switch dependent output */
            if (dwFlags & REPLACE_ADD)
                ConOutResPaging(TRUE,STRING_REPLACE_HELP7);
            else
                ConOutResPaging(TRUE,STRING_REPLACE_HELP3);
        }
        /* Some files replaced */
        else
        {
            /* Add switch dependent output */
            if (dwFlags & REPLACE_ADD)
                ConOutResPrintf(STRING_REPLACE_HELP8, filesReplaced);
            else
                ConOutResPrintf(STRING_REPLACE_HELP4, filesReplaced);
        }
    }
    /* Return memory */
    freep(arg);
    return 1;
}
Пример #4
0
/* If /s switch is specifyed all subdirs has to be considered */
INT recFindSubDirs(DWORD dwFlags,
                   TCHAR szSrcPath[MAX_PATH],
                   TCHAR szDestPath[MAX_PATH],
                   BOOL *doMore)
{
    HANDLE hFile;
    WIN32_FIND_DATA findBuffer;
    TCHAR tmpDestPath[MAX_PATH], tmpSrcPath[MAX_PATH];
    INT filesReplaced = 0;
    INT_PTR i;

    /*
     * Add a wildcard to dest end so the it will be easy to iterate
     * over all the files and directorys in the dest directory.
     */
    _tcscat(szDestPath, _T("*"));

    /* Get the first file in the directory */
    hFile = FindFirstFile (szDestPath, &findBuffer);

    /* Remove the star added earlyer to dest path */
    for(i = (_tcslen(szDestPath) -  1); i > -1; i--)
    {
        if (szDestPath[i] != _T('\\'))
            szDestPath[i] = _T('\0');
        else
            break;
    }

    /* Iterate over all filed directories in the dest dir */
    do
    {
        /* Save the source path so that it will not be wrecked */
        _tcscpy(tmpSrcPath,szSrcPath);
        /* Check for reading problems */
        if (hFile == INVALID_HANDLE_VALUE)
        {
            ConOutFormatMessage (GetLastError(), tmpSrcPath);
            return filesReplaced;
        }

        /*
         * Check if the we should enter the dir or if it is a file
         * or . or .. if so thake the next object to process.
         */
        if (!_tcscmp (findBuffer.cFileName, _T("."))  ||
            !_tcscmp (findBuffer.cFileName, _T(".."))||
            IsExistingFile(findBuffer.cFileName))
            continue;
        /* Add the destpath and the new dir path to tempDestPath */
        _tcscpy(tmpDestPath,szDestPath);
        _tcscat (tmpDestPath, findBuffer.cFileName);
        /* Make sure that we have a directory */
        if (IsExistingDirectory(tmpDestPath))
        {
            /* Add a \ to the end or the path */
            if (szDestPath[_tcslen(tmpDestPath) -  1] != _T('\\'))
                _tcscat(tmpDestPath, _T("\\"));
            /* Call the function to replace files in the new directory */
            filesReplaced += recReplace(dwFlags, tmpSrcPath, tmpDestPath, doMore);
            /* If there were problems break e.g. read-only file */
            if (!*doMore)
                break;
            _tcscpy(tmpSrcPath,szSrcPath);
            /* Controle the next level of subdirs */
            filesReplaced += recFindSubDirs(dwFlags,tmpSrcPath,tmpDestPath, doMore);
            if (!*doMore)
                break;
        }
        /* Get the next handle */
    } while(FindNextFile (hFile, &findBuffer));

    return filesReplaced;
}
Пример #5
0
/* Function to iterate over source files and call replace for each of them */
INT recReplace(DWORD dwFlags,
               TCHAR szSrcPath[MAX_PATH],
               TCHAR szDestPath[MAX_PATH],
               BOOL *doMore)
{
    TCHAR tmpDestPath[MAX_PATH], tmpSrcPath[MAX_PATH];
    INT filesReplaced=0;
    INT_PTR i;
    DWORD dwAttrib = 0;
    HANDLE hFile;
    WIN32_FIND_DATA findBuffer;

    /* Get file handel to the sourcefile(s) */
    hFile = FindFirstFile (szSrcPath, &findBuffer);

    /*
     * Strip the paths back to the folder they are in, so that
     * the different filenames can be added if more than one.
     */
    for(i = (_tcslen(szSrcPath) -  1); i > -1; i--)
    {
        if (szSrcPath[i] != _T('\\'))
            szSrcPath[i] = _T('\0');
        else
            break;
    }

    /* Go through all the soursfiles and copy/replace them */
    do
    {
        if (CheckCtrlBreak(BREAK_INPUT))
        {
            return filesReplaced;
        }

        /* Problem with file handler */
        if (hFile == INVALID_HANDLE_VALUE)
            return filesReplaced;

        /* We do not want to replace any .. . ocr directory */
        if (!_tcscmp (findBuffer.cFileName, _T("."))  ||
                !_tcscmp (findBuffer.cFileName, _T(".."))||
                findBuffer.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
                continue;

        /* Add filename to destpath */
        _tcscpy(tmpDestPath,szDestPath);
        _tcscat (tmpDestPath, findBuffer.cFileName);

        dwAttrib = GetFileAttributes(tmpDestPath);
        /* Check add flag */
        if (dwFlags & REPLACE_ADD)
        {
            if (IsExistingFile(tmpDestPath))
                continue;
            else
                dwAttrib = 0;
        }
        else
        {
            if (!IsExistingFile(tmpDestPath))
                continue;
        }

        /* Check if file is read only, if so check if that should be ignored */
        if (dwAttrib & FILE_ATTRIBUTE_READONLY)
        {
            if (!(dwFlags & REPLACE_READ_ONLY))
            {
                ConOutResPrintf(STRING_REPLACE_ERROR5, tmpDestPath);
                *doMore = FALSE;
                break;
            }
        }

        /* Add filename to sourcepath, insted of wildcards */
        _tcscpy(tmpSrcPath,szSrcPath);
        _tcscat (tmpSrcPath, findBuffer.cFileName);

        /* Make the replace */
        if (replace(tmpSrcPath,tmpDestPath, dwFlags, doMore))
        {
            filesReplaced++;
        }
        else if (!*doMore)
        {
            /* The file to be replaced was the same as the source */
            filesReplaced = -1;
            break;
        }

    /* Take next sourcefile if any */
    } while(FindNextFile (hFile, &findBuffer));

    return filesReplaced;
}
Пример #6
0
INT cmd_move (LPTSTR param)
{
	LPTSTR *arg;
	INT argc, i, nFiles;
	LPTSTR pszDest;
	TCHAR szDestPath[MAX_PATH];
	TCHAR szFullDestPath[MAX_PATH];
	TCHAR szSrcDirPath[MAX_PATH];
	TCHAR szSrcPath[MAX_PATH];
	TCHAR szFullSrcPath[MAX_PATH];
	DWORD dwFlags = 0;
	INT nOverwrite = 0;
	WIN32_FIND_DATA findBuffer;
	HANDLE hFile;
	
	/* used only when source and destination  directories are on different volume*/
	HANDLE hDestFile;
	WIN32_FIND_DATA findDestBuffer;
	TCHAR szMoveDest[MAX_PATH];
	TCHAR szMoveSrc[MAX_PATH];
	LPTSTR pszDestDirPointer;
	LPTSTR pszSrcDirPointer;
	INT nDirLevel = 0;
	
	LPTSTR pszFile;
	BOOL OnlyOneFile;
	BOOL FoundFile;
	BOOL MoveStatus;
	DWORD dwMoveFlags = 0;
	DWORD dwMoveStatusFlags = 0;


	if (!_tcsncmp (param, _T("/?"), 2))
	{
#if 0
		ConOutPuts (_T("Moves files and renames files and directories.\n\n"
			"To move one or more files:\n"
			"MOVE [/N][/Y|/-Y][drive:][path]filename1[,...] destination\n"
			"\n"
			"To rename a directory:\n"
			"MOVE [/N][/Y|/-Y][drive:][path]dirname1 dirname2\n"
			"\n"
			"  [drive:][path]filename1  Specifies the location and name of the file\n"
			"                           or files you want to move.\n"
			"  /N                       Nothing. Don everthing but move files or direcories.\n"
			"  /Y\n"
			"  /-Y\n"
			"..."));
#else
		ConOutResPaging(TRUE,STRING_MOVE_HELP2);
#endif
		return 0;
	}

	nErrorLevel = 0;
	arg = splitspace(param, &argc);

	/* read options */
	for (i = 0; i < argc; i++)
	{
		if (!_tcsicmp(arg[i], _T("/N")))
			dwFlags |= MOVE_NOTHING;
		else if (!_tcsicmp(arg[i], _T("/Y")))
			dwFlags |= MOVE_OVER_YES;
		else if (!_tcsicmp(arg[i], _T("/-Y")))
			dwFlags |= MOVE_OVER_NO;
		else
			break;
	}
	nFiles = argc - i;

	if (nFiles < 1)
	{
		/* there must be at least one pathspec */
		error_req_param_missing();
		freep(arg);
		return 1;
	}

	if (nFiles > 2)
	{
		/* there are more than two pathspecs */
		error_too_many_parameters(param);
		freep(arg);
		return 1;
	}

	/* If no destination is given, default to current directory */
	pszDest = (nFiles == 1) ? _T(".") : arg[i + 1];

	/* check for wildcards in source and destination */
	if (_tcschr(pszDest, _T('*')) != NULL || _tcschr(pszDest, _T('?')) != NULL)
	{
		/* '*'/'?' in dest, this doesnt happen.  give folder name instead*/
		error_invalid_parameter_format(pszDest);
		freep(arg);
		return 1;
	}
	if (_tcschr(arg[i], _T('*')) != NULL || _tcschr(arg[i], _T('?')) != NULL)
	{
		dwMoveStatusFlags |= MOVE_SOURCE_HAS_WILD;
	}
	
	
	/* get destination */
	GetFullPathName (pszDest, MAX_PATH, szDestPath, NULL);
	TRACE ("Destination: %s\n", debugstr_aw(szDestPath));
	
	/* get source folder */
	GetFullPathName(arg[i], MAX_PATH, szSrcDirPath, &pszFile);
	if (pszFile != NULL)
		*pszFile = _T('\0');
	TRACE ("Source Folder: %s\n", debugstr_aw(szSrcDirPath));
	
	hFile = FindFirstFile (arg[i], &findBuffer);
	if (hFile == INVALID_HANDLE_VALUE)
	{
		ErrorMessage (GetLastError (), arg[i]);
		freep (arg);
		return 1;
		
	}

	/* check for special cases "." and ".." and if found skip them */
	FoundFile = TRUE;
	while(FoundFile &&
		  (_tcscmp(findBuffer.cFileName,_T(".")) == 0 ||
		   _tcscmp(findBuffer.cFileName,_T("..")) == 0))
		FoundFile = FindNextFile (hFile, &findBuffer);
	
	if (!FoundFile)
	{
		/* what? we don't have anything to move? */
		error_file_not_found();
		FindClose(hFile);
		freep(arg);
		return 1;
	}
	
	OnlyOneFile = TRUE;
	/* check if there can be found files as files have first priority */
	if (findBuffer.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
		dwMoveStatusFlags |= MOVE_SOURCE_IS_DIR;
	else
		dwMoveStatusFlags |= MOVE_SOURCE_IS_FILE;
	while(OnlyOneFile && FindNextFile(hFile,&findBuffer))
	{
		if (!(findBuffer.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
		{
			ConOutPrintf(_T(""));
			if (dwMoveStatusFlags & MOVE_SOURCE_IS_FILE) OnlyOneFile = FALSE;
			else
			{	/* this has been done this way so that we don't disturb other settings if they have been set before this */
				dwMoveStatusFlags |= MOVE_SOURCE_IS_FILE;
				dwMoveStatusFlags &= ~MOVE_SOURCE_IS_DIR;
			}
		}
	}
	FindClose(hFile);

	TRACE ("Do we have only one file: %s\n", OnlyOneFile ? "TRUE" : "FALSE");

	/* we have to start again to be sure we don't miss any files or folders*/
	hFile = FindFirstFile (arg[i], &findBuffer);
	if (hFile == INVALID_HANDLE_VALUE)
	{
		ErrorMessage (GetLastError (), arg[i]);
		freep (arg);
		return 1;
		
	}
	
	/* check for special cases "." and ".." and if found skip them */
	FoundFile = TRUE;
	while(FoundFile &&
		  (_tcscmp(findBuffer.cFileName,_T(".")) == 0 ||
		   _tcscmp(findBuffer.cFileName,_T("..")) == 0))
		FoundFile = FindNextFile (hFile, &findBuffer);
	
	if (!FoundFile)
	{
		/* huh? somebody removed files and/or folders which were there */
		error_file_not_found();
		FindClose(hFile);
		freep(arg);
		return 1;
	}
	
	/* check if source and destination paths are on different volumes */
	if (szSrcDirPath[0] != szDestPath[0])
		dwMoveStatusFlags |= MOVE_PATHS_ON_DIF_VOL;
	
	/* move it */
	do
	{
		TRACE ("Found file/directory: %s\n", debugstr_aw(findBuffer.cFileName));
		nOverwrite = 1;
		dwMoveFlags = 0;
		dwMoveStatusFlags &= ~MOVE_DEST_IS_FILE &
							~MOVE_DEST_IS_DIR &
							~MOVE_SRC_CURRENT_IS_DIR &
							~MOVE_DEST_EXISTS;
		_tcscpy(szFullSrcPath,szSrcDirPath);
		if(szFullSrcPath[_tcslen(szFullSrcPath) -  1] != _T('\\'))
			_tcscat (szFullSrcPath, _T("\\"));
		_tcscat(szFullSrcPath,findBuffer.cFileName);
		_tcscpy(szSrcPath, szFullSrcPath);
		
		if (IsExistingDirectory(szSrcPath))
		{
			/* source is directory */
			
			if (dwMoveStatusFlags & MOVE_SOURCE_IS_FILE)
			{
				dwMoveStatusFlags |= MOVE_SRC_CURRENT_IS_DIR; /* source is file but at the current round we found a directory */
				continue;
			}
			TRACE ("Source is dir: %s\n", debugstr_aw(szSrcPath));
			dwMoveFlags = MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH | MOVEFILE_COPY_ALLOWED;
		}
		
		/* if source is file we don't need to do anything special */
		
		if (IsExistingDirectory(szDestPath))
		{
			/* destination is existing directory */
			TRACE ("Destination is directory: %s\n", debugstr_aw(szDestPath));
			
			dwMoveStatusFlags |= MOVE_DEST_IS_DIR;
			
			/*build the dest string(accounts for *)*/
			_tcscpy (szFullDestPath, szDestPath);
			/*check to see if there is an ending slash, if not add one*/
			if(szFullDestPath[_tcslen(szFullDestPath) -  1] != _T('\\'))
				_tcscat (szFullDestPath, _T("\\"));
			_tcscat (szFullDestPath, findBuffer.cFileName);
			
			if (IsExistingFile(szFullDestPath) || IsExistingDirectory(szFullDestPath))
				dwMoveStatusFlags |= MOVE_DEST_EXISTS;
			
			dwMoveFlags |= MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH | MOVEFILE_COPY_ALLOWED;
			
		}
		if (IsExistingFile(szDestPath))
		{
			/* destination is a file */
			TRACE ("Destination is file: %s\n", debugstr_aw(szDestPath));
			
			dwMoveStatusFlags |= MOVE_DEST_IS_FILE | MOVE_DEST_EXISTS;
			_tcscpy (szFullDestPath, szDestPath);
			
			dwMoveFlags |= MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH | MOVEFILE_COPY_ALLOWED;
			
		}
		
		TRACE ("Move Status Flags: 0x%X\n",dwMoveStatusFlags);
		
		if (dwMoveStatusFlags & MOVE_SOURCE_IS_DIR &&
			dwMoveStatusFlags & MOVE_DEST_IS_DIR &&
			dwMoveStatusFlags & MOVE_SOURCE_HAS_WILD)
		{
			/* We are not allowed to have existing source and destination dir when there is wildcard in source */
			error_syntax(NULL);
			FindClose(hFile);
			freep(arg);
			return 1;
		}
			
		if (!(dwMoveStatusFlags & (MOVE_DEST_IS_FILE | MOVE_DEST_IS_DIR)))
		{
			/* destination doesn't exist */
			_tcscpy (szFullDestPath, szDestPath);
			if (dwMoveStatusFlags & MOVE_SOURCE_IS_FILE) dwMoveStatusFlags |= MOVE_DEST_IS_FILE;
			if (dwMoveStatusFlags & MOVE_SOURCE_IS_DIR) dwMoveStatusFlags |= MOVE_DEST_IS_DIR;
			
			dwMoveFlags |= MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH | MOVEFILE_COPY_ALLOWED;
		}
		
		if (dwMoveStatusFlags & MOVE_SOURCE_IS_FILE &&
			dwMoveStatusFlags & MOVE_DEST_IS_FILE &&
			!OnlyOneFile)
		{
			/*source has many files but there is only one destination file*/
			error_invalid_parameter_format(pszDest);
			FindClose(hFile);
			freep (arg);
			return 1;
		}
		
		/*checks to make sure user wanted/wants the override*/
		if((dwFlags & MOVE_OVER_NO) &&
		   (dwMoveStatusFlags & MOVE_DEST_EXISTS))
			continue;
		if(!(dwFlags & MOVE_OVER_YES) &&
		    (dwMoveStatusFlags & MOVE_DEST_EXISTS))
			nOverwrite = MoveOverwrite (szFullDestPath);
		if (nOverwrite == PROMPT_NO || nOverwrite == PROMPT_BREAK)
			continue;
		if (nOverwrite == PROMPT_ALL)
			dwFlags |= MOVE_OVER_YES;
		
			
		ConOutPrintf (_T("%s => %s "), szSrcPath, szFullDestPath);
		
		/* are we really supposed to do something */
		if (dwFlags & MOVE_NOTHING)
			continue;
		
		/*move the file*/
		if (!(dwMoveStatusFlags & MOVE_SOURCE_IS_DIR &&
			dwMoveStatusFlags & MOVE_PATHS_ON_DIF_VOL))
			/* we aren't moving source folder to different drive */
			MoveStatus = MoveFileEx (szSrcPath, szFullDestPath, dwMoveFlags);
		else
		{	/* we are moving source folder to different drive */
			_tcscpy(szMoveDest, szFullDestPath);
			_tcscpy(szMoveSrc, szSrcPath);
			DeleteFile(szMoveDest);
			MoveStatus = CreateDirectory(szMoveDest, NULL); /* we use default security settings */
			if (MoveStatus)
			{
				_tcscat(szMoveDest,_T("\\"));
				_tcscat(szMoveSrc,_T("\\"));
				nDirLevel = 0;
				pszDestDirPointer = szMoveDest + _tcslen(szMoveDest);
				pszSrcDirPointer = szMoveSrc + _tcslen(szMoveSrc);
				_tcscpy(pszSrcDirPointer,_T("*.*"));
				hDestFile = FindFirstFile(szMoveSrc, &findDestBuffer);
				if (hDestFile == INVALID_HANDLE_VALUE)
					MoveStatus = FALSE;
				else
				{
					BOOL FirstTime = TRUE;
					FoundFile = TRUE;
					MoveStatus = FALSE;
					while(FoundFile)
					{
						if (FirstTime)
							FirstTime = FALSE;
						else
							FoundFile = FindNextFile (hDestFile, &findDestBuffer);
						
						if (!FoundFile)
						{	/* Nothing to do in this folder so we stop working on it */
							FindClose(hDestFile);
							(pszSrcDirPointer)--;
							(pszDestDirPointer)--;
							_tcscpy(pszSrcDirPointer,_T(""));
							_tcscpy(pszDestDirPointer,_T(""));
							if (nDirLevel > 0)
							{
								TCHAR szTempPath[MAX_PATH];
								INT nDiff;

								FoundFile = TRUE; /* we need to continue our seek for files */
								nDirLevel--;
								RemoveDirectory(szMoveSrc);
								GetDirectory(szMoveSrc,szTempPath,0);
								nDiff = _tcslen(szMoveSrc) - _tcslen(szTempPath);
								pszSrcDirPointer = pszSrcDirPointer - nDiff;
								_tcscpy(pszSrcDirPointer,_T(""));
								GetDirectory(szMoveDest,szTempPath,0);
								nDiff = _tcslen(szMoveDest) - _tcslen(szTempPath);
								pszDestDirPointer = pszDestDirPointer - nDiff;
								_tcscpy(pszDestDirPointer,_T(""));
								if(szMoveSrc[_tcslen(szMoveSrc) -  1] != _T('\\'))
									_tcscat (szMoveSrc, _T("\\"));
								if(szMoveDest[_tcslen(szMoveDest) -  1] != _T('\\'))
									_tcscat (szMoveDest, _T("\\"));
								pszDestDirPointer = szMoveDest + _tcslen(szMoveDest);
								pszSrcDirPointer = szMoveSrc + _tcslen(szMoveSrc);
								_tcscpy(pszSrcDirPointer,_T("*.*"));
								hDestFile = FindFirstFile(szMoveSrc, &findDestBuffer);
								if (hDestFile == INVALID_HANDLE_VALUE)
									continue;
								FirstTime = TRUE;
							}
							else
							{
								MoveStatus = TRUE; /* we moved everything so lets tell user about it */
								RemoveDirectory(szMoveSrc);
							}
							continue;
						}
						
						/* if we find "." or ".." we'll skip them */
						if (_tcscmp(findDestBuffer.cFileName,_T(".")) == 0 ||
							_tcscmp(findDestBuffer.cFileName,_T("..")) == 0)
							continue;
					
						_tcscpy(pszSrcDirPointer, findDestBuffer.cFileName);
						_tcscpy(pszDestDirPointer, findDestBuffer.cFileName);
						if (IsExistingFile(szMoveSrc))
						{
							FoundFile = CopyFile(szMoveSrc, szMoveDest, FALSE);
							if (!FoundFile) continue;
							DeleteFile(szMoveSrc);
						}
						else
						{
							FindClose(hDestFile);
							CreateDirectory(szMoveDest, NULL);
							_tcscat(szMoveDest,_T("\\"));
							_tcscat(szMoveSrc,_T("\\"));
							nDirLevel++;
							pszDestDirPointer = szMoveDest + _tcslen(szMoveDest);
							pszSrcDirPointer = szMoveSrc + _tcslen(szMoveSrc);
							_tcscpy(pszSrcDirPointer,_T("*.*"));
							hDestFile = FindFirstFile(szMoveSrc, &findDestBuffer);
							if (hDestFile == INVALID_HANDLE_VALUE)
							{
								FoundFile = FALSE;
								continue;
							}
							FirstTime = TRUE;
						}
					}
				}
			}
		}
		if (MoveStatus)
			ConOutResPrintf(STRING_MOVE_ERROR1);
		else
			ConOutResPrintf(STRING_MOVE_ERROR2);
	}
	while ((!OnlyOneFile || dwMoveStatusFlags & MOVE_SRC_CURRENT_IS_DIR ) &&
			!(dwMoveStatusFlags & MOVE_SOURCE_IS_DIR) &&
			FindNextFile (hFile, &findBuffer));
	FindClose (hFile);
	
	freep (arg);
	return 0;
}
Пример #7
0
INT
copy(TCHAR source[MAX_PATH],
     TCHAR dest[MAX_PATH],
     INT append,
     DWORD lpdwFlags,
     BOOL bTouch)
{
    FILETIME srctime,NewFileTime;
    HANDLE hFileSrc;
    HANDLE hFileDest;
    LPBYTE buffer;
    DWORD  dwAttrib;
    DWORD  dwRead;
    DWORD  dwWritten;
    BOOL   bEof = FALSE;
    TCHAR TrueDest[MAX_PATH];
    TCHAR TempSrc[MAX_PATH];
    TCHAR * FileName;
    SYSTEMTIME CurrentTime;

    /* Check Breaker */
    if (CheckCtrlBreak(BREAK_INPUT))
        return 0;

    TRACE ("checking mode\n");

    if (bTouch)
    {
        hFileSrc = CreateFile (source, GENERIC_WRITE, FILE_SHARE_READ,
            NULL, OPEN_EXISTING, 0, NULL);
        if (hFileSrc == INVALID_HANDLE_VALUE)
        {
            ConOutResPrintf(STRING_COPY_ERROR1, source);
            nErrorLevel = 1;
            return 0;
        }

        GetSystemTime(&CurrentTime);
        SystemTimeToFileTime(&CurrentTime, &NewFileTime);
        if (SetFileTime(hFileSrc,(LPFILETIME) NULL, (LPFILETIME) NULL, &NewFileTime))
        {
            CloseHandle(hFileSrc);
            nErrorLevel = 1;
            return 1;

        }
        else
        {
            CloseHandle(hFileSrc);
            return 0;
        }
    }

    dwAttrib = GetFileAttributes (source);

    hFileSrc = CreateFile (source, GENERIC_READ, FILE_SHARE_READ,
        NULL, OPEN_EXISTING, 0, NULL);
    if (hFileSrc == INVALID_HANDLE_VALUE)
    {
        ConOutResPrintf(STRING_COPY_ERROR1, source);
        nErrorLevel = 1;
        return 0;
    }

    TRACE ("getting time\n");

    GetFileTime (hFileSrc, &srctime, NULL, NULL);

    TRACE ("copy: flags has %s\n",
        lpdwFlags & COPY_ASCII ? "ASCII" : "BINARY");

    /* Check to see if /D or /Z are true, if so we need a middle
       man to copy the file too to allow us to use CopyFileEx later */
    if (lpdwFlags & COPY_DECRYPT)
    {
        GetEnvironmentVariable(_T("TEMP"),TempSrc,MAX_PATH);
        _tcscat(TempSrc,_T("\\"));
        FileName = _tcsrchr(source,_T('\\'));
        FileName++;
        _tcscat(TempSrc,FileName);
        /* This is needed to be on the end to prevent an error
           if the user did "copy /D /Z foo bar then it would be copied
           too %TEMP%\foo here and when %TEMP%\foo when it sets it up
           for COPY_RESTART, this would mean it is copying to itself
           which would error when it tried to open the handles for ReadFile
           and WriteFile */
        _tcscat(TempSrc,_T(".decrypt"));
        if (!CopyFileEx(source, TempSrc, NULL, NULL, FALSE, COPY_FILE_ALLOW_DECRYPTED_DESTINATION))
        {
            CloseHandle (hFileSrc);
            nErrorLevel = 1;
            return 0;
        }
        _tcscpy(source, TempSrc);
    }


    if (lpdwFlags & COPY_RESTART)
    {
        _tcscpy(TrueDest, dest);
        GetEnvironmentVariable(_T("TEMP"),dest,MAX_PATH);
        _tcscat(dest,_T("\\"));
        FileName = _tcsrchr(TrueDest,_T('\\'));
        FileName++;
        _tcscat(dest,FileName);
    }


    if (!IsExistingFile (dest))
    {
        TRACE ("opening/creating\n");
        hFileDest =
            CreateFile (dest, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
    }
    else if (!append)
    {
        TRACE ("SetFileAttributes (%s, FILE_ATTRIBUTE_NORMAL);\n", debugstr_aw(dest));
        SetFileAttributes (dest, FILE_ATTRIBUTE_NORMAL);

        TRACE ("DeleteFile (%s);\n", debugstr_aw(dest));
        DeleteFile (dest);

        hFileDest =	CreateFile (dest, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
    }
    else
    {
        LONG lFilePosHigh = 0;

        if (!_tcscmp (dest, source))
        {
            CloseHandle (hFileSrc);
            return 0;
        }

        TRACE ("opening/appending\n");
        SetFileAttributes (dest, FILE_ATTRIBUTE_NORMAL);

        hFileDest =
            CreateFile (dest, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);

        /* Move to end of file to start writing */
        SetFilePointer (hFileDest, 0, &lFilePosHigh,FILE_END);
    }


    if (hFileDest == INVALID_HANDLE_VALUE)
    {
        CloseHandle (hFileSrc);
        ConOutResPuts(STRING_ERROR_PATH_NOT_FOUND);
        nErrorLevel = 1;
        return 0;
    }

    /* A page-aligned buffer usually give more speed */
    buffer = VirtualAlloc(NULL, BUFF_SIZE, MEM_COMMIT, PAGE_READWRITE);
    if (buffer == NULL)
    {
        CloseHandle (hFileDest);
        CloseHandle (hFileSrc);
        ConOutResPuts(STRING_ERROR_OUT_OF_MEMORY);
        nErrorLevel = 1;
        return 0;
    }

    do
    {
        ReadFile (hFileSrc, buffer, BUFF_SIZE, &dwRead, NULL);
        if (lpdwFlags & COPY_ASCII)
        {
            LPBYTE pEof = memchr(buffer, 0x1A, dwRead);
            if (pEof != NULL)
            {
                bEof = TRUE;
                dwRead = pEof-buffer+1;
                break;
            }
        }

        if (dwRead == 0)
            break;

        WriteFile (hFileDest, buffer, dwRead, &dwWritten, NULL);
        if (dwWritten != dwRead || CheckCtrlBreak(BREAK_INPUT))
        {
            ConOutResPuts(STRING_COPY_ERROR3);

            VirtualFree (buffer, 0, MEM_RELEASE);
            CloseHandle (hFileDest);
            CloseHandle (hFileSrc);
            nErrorLevel = 1;
            return 0;
        }
    }
    while (!bEof);

    TRACE ("setting time\n");
    SetFileTime (hFileDest, &srctime, NULL, NULL);

    if ((lpdwFlags & COPY_ASCII) && !bEof)
    {
        /* we're dealing with ASCII files! */
        buffer[0] = 0x1A;
        TRACE ("appending ^Z\n");
        WriteFile (hFileDest, buffer, sizeof(CHAR), &dwWritten, NULL);
    }

    VirtualFree (buffer, 0, MEM_RELEASE);
    CloseHandle (hFileDest);
    CloseHandle (hFileSrc);

    TRACE ("setting mode\n");
    SetFileAttributes (dest, dwAttrib);

    /* Now finish off the copy if needed with CopyFileEx */
    if (lpdwFlags & COPY_RESTART)
    {
        if (!CopyFileEx(dest, TrueDest, NULL, NULL, FALSE, COPY_FILE_RESTARTABLE))
        {
            nErrorLevel = 1;
            DeleteFile(dest);
            return 0;
        }
        /* Take care of file in the temp folder */
        DeleteFile(dest);

    }

    if (lpdwFlags & COPY_DECRYPT)
        DeleteFile(TempSrc);

    return 1;
}
Пример #8
0
INT cmd_copy(LPTSTR param)
{
    LPTSTR *arg;
    INT argc, i, nFiles, nOverwrite = 0, nSrc = -1, nDes = -1;
    /* this is the path up to the folder of the src and dest ie C:\windows\ */
    TCHAR szDestPath[MAX_PATH];
    TCHAR szSrcPath[MAX_PATH];
    DWORD dwFlags = 0;
    /* If this is the type of copy where we are adding files */
    BOOL bAppend = FALSE;
    WIN32_FIND_DATA findBuffer;
    HANDLE hFile = NULL;
    BOOL bTouch = FALSE;
    /* Used when something like "copy c*.exe d*.exe" during the process of
       figuring out the new name */
    /* Pointer to keep track of how far through the append input(file1+file2+file3) we are */
    TCHAR  * appendPointer = _T("\0");
    /* The full path to src and dest.  This has drive letter, folders, and filename */
    TCHAR tmpDestPath[MAX_PATH];
    TCHAR tmpSrcPath[MAX_PATH];
    /* A bool on weather or not the destination name will be taking from the input */
    BOOL bSrcName = FALSE;
    /* Seems like a waste but it is a pointer used to copy from input to PreserveName */
    TCHAR * UseThisName;
    /* for CMDCOPY env */
    TCHAR *evar;
    int size;
    TCHAR * szTouch;
    BOOL bHasWildcard, bDone = FALSE, bMoreFiles = FALSE;
    BOOL bMultipleSource = FALSE, bMultipleDest = FALSE;


    /* Show help/usage info */
    if (!_tcsncmp(param, _T("/?"), 2))
    {
        ConOutResPaging(TRUE, STRING_COPY_HELP2);
        return 0;
    }

    nErrorLevel = 0;

    /* Get the envor value if it exists */
    evar = cmd_alloc(512 * sizeof(TCHAR));
    if (evar == NULL)
        size = 0;
    else
        size = GetEnvironmentVariable (_T("COPYCMD"), evar, 512);

    if (size > 512)
    {
        TCHAR *old_evar = evar;
        evar = cmd_realloc(evar,size * sizeof(TCHAR) );
        if (evar!=NULL)
            size = GetEnvironmentVariable (_T("COPYCMD"), evar, size);
        else
        {
            size=0;
            evar = old_evar;
        }
    }

    /* check see if we did get any env variable */
    if (size != 0)
    {
        int t = 0;

        /* scan and set the flags */
        for (t = 0; t < size; t++)
        {
            if (_tcsncicmp(_T("/A"),&evar[t],2) == 0)
            {
                dwFlags |=COPY_ASCII;
                t++;
            }
            else if (_tcsncicmp(_T("/B"),&evar[t],2) == 0)
            {
                dwFlags |= COPY_BINARY;
                t++;
            }
            else if (_tcsncicmp(_T("/D"),&evar[t],2) == 0)
            {
                dwFlags |= COPY_DECRYPT;
                t++;
            }
            else if (_tcsncicmp(_T("/V"),&evar[t],2) == 0)
            {
                dwFlags |= COPY_VERIFY;
                t++;
            }
            else if (_tcsncicmp(_T("/N"),&evar[t],2) == 0)
            {
                dwFlags |= COPY_SHORTNAME;
                t++;
            }
            else if (_tcsncicmp(_T("/Y"),&evar[t],2) == 0)
            {
                dwFlags |= COPY_NO_PROMPT;
                t++;
            }
            else if (_tcsncicmp(_T("/-Y"),&evar[t],3) == 0)
            {
                dwFlags |= COPY_PROMPT;
                t+=2;
            }
            else if (_tcsncicmp(_T("/Z"),&evar[t],2) == 0)
            {
                dwFlags |= COPY_PROMPT;
                t++;
            }
        }
    }
    cmd_free(evar);


    /* Split the user input into array */
    arg = split(param, &argc, FALSE, TRUE);
    nFiles = argc;

    /* Read switches and count files */
    for (i = 0; i < argc; i++)
    {
        if (*arg[i] == _T('/'))
        {
            if (_tcslen(arg[i]) >= 2)
            {
                switch (_totupper(arg[i][1]))
                {
                    case _T('A'):
                        dwFlags |= COPY_ASCII;
                        break;

                    case _T('B'):
                        dwFlags |= COPY_BINARY;
                        break;

                    case _T('D'):
                        dwFlags |= COPY_DECRYPT;
                        break;

                    case _T('V'):
                        dwFlags |= COPY_VERIFY;
                        break;

                    case _T('N'):
                        dwFlags |= COPY_SHORTNAME;
                        break;

                    case _T('Y'):
                        dwFlags |= COPY_NO_PROMPT;
                        dwFlags &= ~COPY_PROMPT;
                        break;

                    case _T('-'):
                        if (_tcslen(arg[i]) >= 3)
                            if (_totupper(arg[i][2]) == _T('Y'))
                            {
                                dwFlags &= ~COPY_NO_PROMPT;
                                dwFlags |= COPY_PROMPT;
                            }

                            break;

                    case _T('Z'):
                        dwFlags |= COPY_RESTART;
                        break;

                    default:
                        /* Invalid switch */
                        ConOutResPrintf(STRING_ERROR_INVALID_SWITCH, _totupper(arg[i][1]));
                        nErrorLevel = 1;
                        freep (arg);
                        return 1;
                        break;
                }
            }
            /* If it was a switch, subtract from total arguments */
            nFiles--;
        }
        else
        {
            /* If it isn't a switch then it is the source or destination */
            if (nSrc == -1)
            {
                nSrc = i;
            }
            else if (*arg[i] == _T('+'))
            {
                /* Next file should be appended */
                bMoreFiles = TRUE;
                nFiles -= 1;
            }
            else if (bMoreFiles)
            {
                /* Add this file to the source string
                   this way we can do all checks
                    directly on source string later on */
                TCHAR * ptr;
                int length = (_tcslen(arg[nSrc]) + _tcslen(arg[i]) + 2) * sizeof(TCHAR);
                ptr = cmd_alloc(length);
                if (ptr)
                {
                    _tcscpy(ptr, arg[nSrc]);
                    _tcscat(ptr, _T("|"));
                    _tcscat(ptr, arg[i]);
                    cmd_free(arg[nSrc]);
                    arg[nSrc] = ptr;
                    nFiles -= 1;
                }

                bMoreFiles = FALSE;
            }
            else if (nDes == -1)
            {
                nDes = i;
            }
        }
    }

    /* keep quiet within batch files */
    if (bc != NULL)
    {
        dwFlags |= COPY_NO_PROMPT;
        dwFlags &= ~COPY_PROMPT;
    }

    if (nFiles < 1)
    {
        /* There are not enough files, there has to be at least 1 */
        ConOutResPuts(STRING_ERROR_REQ_PARAM_MISSING);
        freep(arg);
        return 1;
    }

    if (nFiles > 2)
    {
        /* There are too many file names in command */
        ConErrResPrintf(STRING_ERROR_TOO_MANY_PARAMETERS,_T(""));
        nErrorLevel = 1;
        freep(arg);
        return 1;
    }

    if ((_tcschr(arg[nSrc], _T('|')) != NULL) ||
        (_tcschr(arg[nSrc], _T('*')) != NULL) ||
        (_tcschr(arg[nSrc], _T('?')) != NULL) ||
        IsExistingDirectory(arg[nSrc]))
    {
        bMultipleSource = TRUE;
    }

    /* Reusing the number of files variable */
    nFiles = 0;

    /* Check if no destination argument is passed */
    if (nDes == -1)
    {
        /* If no destination was entered then just use
        the current directory as the destination */
        GetCurrentDirectory(MAX_PATH, szDestPath);
    }
    else
    {
        /* Check if the destination is 'x:' */
        if ((arg[nDes][1] == _T(':')) && (arg[nDes][2] == _T('\0')))
        {
            GetRootPath(arg[nDes], szDestPath, MAX_PATH);
        }
        else
        {
            /* If the user entered two file names then form the full string path */
            GetFullPathName(arg[nDes], MAX_PATH, szDestPath, NULL);
        }

        /* Make sure there is an ending slash to the path if the dest is a folder */
        if ((_tcschr(szDestPath, _T('*')) == NULL) &&
            IsExistingDirectory(szDestPath))
        {
            bMultipleDest = TRUE;
            if (szDestPath[_tcslen(szDestPath) -  1] != _T('\\'))
                _tcscat(szDestPath, _T("\\"));
        }

        /* Check if the destination uses wildcards */
        if ((_tcschr(arg[nDes], _T('*')) != NULL) ||
            (_tcschr(arg[nDes], _T('?')) != NULL))
        {
            bMultipleDest = TRUE;
        }
    }

    if (nDes != -1) /* you can only append files when there is a destination */
    {
        if (bMultipleSource && !bMultipleDest)
        {
            /* We have multiple source files, but not multiple destination
               files. This means we are appending the soruce files. */
            bAppend = TRUE;
            if (_tcschr(arg[nSrc], _T('|')) != NULL)
                appendPointer = arg[nSrc];
        }
    }

    /* Save the name the user entered */
    UseThisName = _tcsrchr(szDestPath,_T('\\'));
    if (UseThisName)
    {
        /* Split the name from the path */
        *UseThisName++ = _T('\0');

        /* Check if the dest path ends with '\*' or '\' */
        if (((UseThisName[0] == _T('*')) && (UseThisName[1] == _T('\0'))) ||
            (UseThisName[0] == _T('\0')))
        {
            /* In this case we will be using the same name as the source file
            for the destination file because destination is a folder */
            bSrcName = TRUE;
            UseThisName = NULL;
        }
    }
    else
    {
        /* Something's seriously wrong! */
        UseThisName = szDestPath;
    }

    do
    {
        /* Get the full string of the path to the source file */
        if (_tcschr(arg[nSrc], _T('|')) != NULL)
        {
            /* Reset the source path */
            szSrcPath[0] = _T('\0');

            /* Loop through the source file name and copy all
            the chars one at a time until it gets too + */
            while(TRUE)
            {
                if (appendPointer[0] == _T('|'))
                {
                    /* Skip the | and go to the next file name */
                    appendPointer++;
                    break;
                }
                else if (appendPointer[0] == _T('\0'))
                {
                    bDone = TRUE;
                    break;
                }

                _tcsncat(szSrcPath, appendPointer, 1);
                appendPointer++;
            }

            if (_tcschr(arg[nSrc], _T(',')) != NULL)
            {
                /* Only time there is a , in the source is when they are using touch
                   Cant have a destination and can only have on ,, at the end of the string
                    Cant have more then one file name */
                szTouch = _tcsstr(arg[nSrc], _T("|"));
                if (_tcsncmp(szTouch,_T("|,,\0"), 4) || (nDes != -1))
                {
                    ConErrResPrintf(STRING_ERROR_INVALID_PARAM_FORMAT,arg[nSrc]);
                    nErrorLevel = 1;
                    freep (arg);
                    return 1;
                }
                bTouch = TRUE;
                bDone = TRUE;
            }
        }
        else
        {
            bDone = TRUE;
            _tcscpy(szSrcPath, arg[nSrc]);
        }

        /* "x:" is not a valid source path format. */
        if ((szSrcPath[1] == _T(':')) && (szSrcPath[2] == _T('\0')))
        {
            ConOutPrintf(_T("%s\n"), szSrcPath);
            ConOutFormatMessage(ERROR_FILE_NOT_FOUND, szSrcPath);
            nErrorLevel = 1;
            break;
        }


        /* From this point on, we can assume that the shortest path is 3 letters long
        and that would be [DriveLetter]:\ */

        /* Check if the path has a wildcard */
        bHasWildcard = (_tcschr(szSrcPath, _T('*')) != NULL);

        /* If there is no * in the path name and it is a folder then we will
           need to add a wildcard to the pathname so FindFirstFile comes up
           with all the files in that folder */
        if (!bHasWildcard && IsExistingDirectory(szSrcPath))
        {
            /* If it doesnt have a \ at the end already then on needs to be added */
            if (szSrcPath[_tcslen(szSrcPath) -  1] != _T('\\'))
                _tcscat(szSrcPath, _T("\\"));
            _tcscat(szSrcPath, _T("*"));
            bHasWildcard = TRUE;
        }

        /* If the path ends with '\' add a wildcard at the end */
        if (szSrcPath[_tcslen(szSrcPath) -  1] == _T('\\'))
        {
            _tcscat(szSrcPath, _T("*"));
            bHasWildcard = TRUE;
        }

        /* Get a list of all the files */
        hFile = FindFirstFile(szSrcPath, &findBuffer);

        /* If it couldnt open the file handle, print out the error */
        if (hFile == INVALID_HANDLE_VALUE)
        {
            /* only print source name when more then one file */
            if (bMultipleSource)
                ConOutPrintf(_T("%s\n"), szSrcPath);

            ConOutFormatMessage(GetLastError(), szSrcPath);
            freep(arg);
            nErrorLevel = 1;
            return 1;
        }

        /* Strip the paths back to the folder they are in */
        for (i = (_tcslen(szSrcPath) -  1); i > -1; i--)
            if (szSrcPath[i] != _T('\\'))
                szSrcPath[i] = _T('\0');
            else
                break;

        do
        {
            /* Check Breaker */
            if (CheckCtrlBreak(BREAK_INPUT))
            {
                FindClose(hFile);
                freep(arg);
                return 1;
            }

            /* Set the override to yes each new file */
            nOverwrite = 1;

            /* Ignore the . and .. files */
            if (!_tcscmp(findBuffer.cFileName, _T("."))  ||
                !_tcscmp(findBuffer.cFileName, _T("..")) ||
                findBuffer.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
            {
                continue;
            }

            /* Copy the base folder over to a tmp string */
            _tcscpy(tmpDestPath, szDestPath);
            _tcscat(tmpDestPath, _T("\\"));

            /* Can't put a file into a folder that isn't there */
            if (_tcscmp(tmpDestPath, _T("\\\\.\\")) &&
                !IsExistingDirectory(tmpDestPath))
            {
                FindClose(hFile);
                ConOutFormatMessage(GetLastError(), szSrcPath);
                freep(arg);
                nErrorLevel = 1;
                return 1;
            }

            /* Copy over the destination path name */
            if (bSrcName)
                _tcscat(tmpDestPath, findBuffer.cFileName);
            else
            {
                /* If there is no wildcard you can use the name the user entered */
                if ((_tcschr(UseThisName, _T('*')) == NULL) &&
                    (_tcschr(UseThisName, _T('?')) == NULL))
                {
                    _tcscat(tmpDestPath, UseThisName);
                }
                else
                {
                    TCHAR DoneFile[MAX_PATH];

                    BuildFileName(findBuffer.cFileName,
                                  UseThisName,
                                  DoneFile);


                    /* Add the filename to the tmp string path */
                    _tcscat(tmpDestPath, DoneFile);
                }
            }

            /* Build the string path to the source file */
            _tcscpy(tmpSrcPath,szSrcPath);
            _tcscat (tmpSrcPath, findBuffer.cFileName);

            /* Check to see if the file is the same file */
            if (!bTouch && !_tcscmp(tmpSrcPath, tmpDestPath))
            {
                ConOutResPrintf(STRING_COPY_ERROR2);

                nErrorLevel = 1;
                break;
            }

            /* only print source name when more then one file */
            if (bMultipleSource)
                ConOutPrintf(_T("%s\n"), tmpSrcPath);

            /* Handle any overriding / prompting that needs to be done */
            if (((!(dwFlags & COPY_NO_PROMPT) && IsExistingFile (tmpDestPath)) || dwFlags & COPY_PROMPT) && !bTouch)
                nOverwrite = CopyOverwrite(tmpDestPath);
            if (nOverwrite == PROMPT_NO || nOverwrite == PROMPT_BREAK)
                continue;
            if (nOverwrite == PROMPT_ALL || (nOverwrite == PROMPT_YES && bAppend))
                dwFlags |= COPY_NO_PROMPT;

            /* Tell weather the copy was successful or not */
            if (copy(tmpSrcPath,tmpDestPath, bAppend, dwFlags, bTouch))
            {
                nFiles++;
                //LoadString(CMD_ModuleHandle, STRING_MOVE_ERROR1, szMsg, RC_STRING_MAX_SIZE);
            }
            else
            {
                /* print out the error message */
                ConOutResPrintf(STRING_COPY_ERROR3);
                ConOutFormatMessage (GetLastError(), szSrcPath);
                nErrorLevel = 1;
            }

        /* Loop through all wildcard files */
        } while (FindNextFile(hFile, &findBuffer));

    /* Loop through all files in src string with a + */
    } while(!bDone);

    /* print out the number of files copied */
    ConOutResPrintf(STRING_COPY_FILE, bAppend ? 1 : nFiles);

    if (hFile) FindClose(hFile);

    if (arg != NULL)
        freep(arg);

    return 0;
}