我正在用 C 语言编写这段代码,首先找出登录的用户,然后从该用户的 AppData 中复制一些文件。 我能够找到用户,我能够生成路径,但问题是我不知道如何使用 C 复制文件夹及其内容,所以我想到了使用 System() 命令。 但是现在如果我使用 COPY 命令,它说路径不正确,而实际上它是正确的并且如果我在 CMD 上使用相同的命令则工作正常。 此外,如果我使用 XCOPY,它会说该命令未被识别为内部或外部命令,而 XCOPY 在 CMD 上运行良好。
有人能告诉我如何实际复制文件夹及其内容吗?
我正在压缩部分代码以生成文件路径和复制命令。
//making path variable
char path[100];
strcat(path,"C:\\Users\\");
strcat(path,username); //username is variable it gets value from function
strcat(path,"\\AppData\\Local\\Google\\Chrome\\*.*");
printf(path);
char command[100];
strcat(command,"copy ");
strcat(command,path);
strcat(command," D:\\myFolder");
printf("\n");
printf(command);
printf("\n");
system(command);
更新
这是我的完整代码,有人可以让它工作吗?
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <windows.h>
#include <Lmcons.h>
int main()
{
//getting current user
TCHAR username[UNLEN+1];
DWORD len = UNLEN+1;
GetUserName(username, &len);
printf(username);
printf("\n");
//making path variable
char path[100];
strcpy(path,"C:\\Users\\");
strcat(path,username);
strcat(path,"\\AppData\\Local\\Google\\Chrome\\*.*");
printf(path);
//listing dir
DIR *dfd = opendir(path);
struct dirent *dp;
if(dfd != NULL) {
while((dp = readdir(dfd)) != NULL)
printf("%s\n", dp->d_name);
closedir(dfd);
}
char command[100];
strcpy(command,"copy ");
strcat(command,path);
strcat(command," D:\\myFolder\\");
printf("\n");
printf(command);
printf("\n");
//sprintf(command, "copy %s/*.* D:/myfolder",path);
system(command);
return 0;
}
最佳答案
您正在使用未初始化的数组。
改变
strcat(path,"C:\\Users\\");
strcat(command,"copy ");
到
strcpy(path,"C:\\Users\\");
strcpy(command,"copy ");
关于c - Windows 复制命令如 XCOPY、COPY、ROBOCOPY 在 System() 中的 C 语言中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15621670/