#include #include #include static void printHelp(); static bool copyDirRecursively( const char *srcPath, const char *dstPath ); int main(int argc, char *argv[]) { /* printf("argc=%d\n", argc); for (int i = 0; i < argc; ++i) { printf("argv[%d]=\"%s\" (length=%d)\n", i, argv[i], strlen(argv[i])); } */ if (argc < 3) { printHelp(); return 1; } DWORD attr = GetFileAttributes(argv[1]); if (attr == INVALID_FILE_ATTRIBUTES) { printf("Illegal source directory.\n"); return (-1); } else if ((attr & FILE_ATTRIBUTE_DIRECTORY) == 0) { printf("Source is not a directory.\n"); return (-1); } attr = GetFileAttributes(argv[2]); if (attr == INVALID_FILE_ATTRIBUTES) { printf("Illegal destination directory.\n"); return (-1); } else if ((attr & FILE_ATTRIBUTE_DIRECTORY) == 0) { printf("Destination is not a directory.\n"); return (-1); } if (!copyDirRecursively(argv[1], argv[2])) return (-1); return 0; } static void printHelp() { printf( "Copy contents of a directory recursively.\n" "Usage:\n" "\trcopy sourceDir destinationDir\n" ); } static bool copyDirRecursively( const char *srcPath, const char *dstPath ) { DWORD attr = GetFileAttributes(srcPath); if ( attr == INVALID_FILE_ATTRIBUTES || (attr & FILE_ATTRIBUTE_DIRECTORY) == 0 ) { return false; } attr = GetFileAttributes(dstPath); if ( attr == INVALID_FILE_ATTRIBUTES || (attr & FILE_ATTRIBUTE_DIRECTORY) == 0 ) { return false; } char srcFile[MAX_PATH]; strcpy(srcFile, srcPath); size_t len = strlen(srcFile); if (len == 0) return false; if (srcFile[len-1] != '\\' && srcFile[len-1] != '/') strcat(srcFile, "\\"); int srcLen = strlen(srcFile); char pattern[MAX_PATH]; strcpy(pattern, srcFile); strcat(pattern, "*"); char dstFile[MAX_PATH]; strcpy(dstFile, dstPath); len = strlen(dstFile); if (len == 0) return false; if (dstFile[len-1] != '\\' && dstFile[len-1] != '/') strcat(dstFile, "\\"); size_t dstLen = strlen(dstFile); WIN32_FIND_DATA findData; HANDLE h; h = FindFirstFile(pattern, &findData); while (h != INVALID_HANDLE_VALUE) { if ( strcmp(findData.cFileName, "..") != 0 && strcmp(findData.cFileName, ".") != 0 ) { strcpy(srcFile + srcLen, findData.cFileName); strcpy(dstFile + dstLen, findData.cFileName); printf("%s -> %s\n", srcFile, dstFile); if ( (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0 ) { // Make subdirectory in destination directory if (!CreateDirectory( dstFile, NULL )) { DWORD err = GetLastError(); if (err != 0 && err != ERROR_ALREADY_EXISTS) { printf("Cannot create a directory, err=%d\n", err); return false; } } if (!copyDirRecursively( srcFile, dstFile )) { printf( "Failed to copy subdirectory %s\n", findData.cFileName ); return false; } } else { // Normal file if (!CopyFile(srcFile, dstFile, FALSE)) { printf( "Cannot copy the file %s\n", findData.cFileName ); return false; } } } if (!FindNextFile(h, &findData)) break; } FindClose(h); return true; }