我有以下代码来复制文件
sprintf(command, "copy /Y %s %s", sourceFile, targetFile);
system(command);
它的工作原理除了显示的dos窗口非常烦人。
我正在尝试使用CreateProcess()(对于WINNT使用#ifdef),但不确定如何设置相同的命令行。 在没有显示dos窗口的情况下,在C(在Windows上)复制文件的任何其他选项?
答案 0 :(得分:7)
Windows为此提供了CopyFile
系列API。
答案 1 :(得分:2)
这是我从this website解除的一些代码。您可以将其包装到您自己的函数中,只需传递源文件路径和目标文件路径(在此示例中为argv[1]
和argv[2
)
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
FILE *from, *to;
char ch;
if(argc!=3) {
printf("Usage: copy <source> <destination>\n");
exit(1);
}
/* open source file */
if((from = fopen(argv[1], "rb"))==NULL) {
printf("Cannot open source file.\n");
exit(1);
}
/* open destination file */
if((to = fopen(argv[2], "wb"))==NULL) {
printf("Cannot open destination file.\n");
exit(1);
}
/* copy the file */
while(!feof(from)) {
ch = fgetc(from);
if(ferror(from)) {
printf("Error reading source file.\n");
exit(1);
}
if(!feof(from)) fputc(ch, to);
if(ferror(to)) {
printf("Error writing destination file.\n");
exit(1);
}
}
if(fclose(from)==EOF) {
printf("Error closing source file.\n");
exit(1);
}
if(fclose(to)==EOF) {
printf("Error closing destination file.\n");
exit(1);
}
return 0;
}
答案 2 :(得分:2)
将ShellExecute与SW_HIDE一起使用 http://msdn.microsoft.com/en-us/library/bb762153(VS.85).aspx
答案 3 :(得分:0)
有些库可以做到,或者你可以自己编写代码,使用缓冲区和fread / fwrite。我上次写C代码已经很长时间了,所以我不记得确切的语法。
答案 4 :(得分:0)
#include<windows.h>
#include<tchar.h>
#include<shellapi.h>
#define _UNICODE
int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance,
PSTR szCmdLine, int iCmdShow)
{
SHFILEOPSTRUCT s={0};
s.hwnd = GetFocus();
s.wFunc = FO_COPY;
s.pFrom = _T("d:\\songs\\vineel\\telugu\0\0");
s.pTo = _T("d:\0");
s.fFlags = 0;
s.lpszProgressTitle = _T("Vineel From Shell - Feeling the power of WIN32 API");
SHFileOperation(&s);
}
上面的代码将调用explorer copy handler .....