如何在不显示DOS窗口的情况下复制文件

3
我有以下代码来复制文件
sprintf(command, "copy /Y %s %s", sourceFile, targetFile);
system(command);

除了弹出的命令行窗口,它能正常工作,这非常令人烦恼。

我正在尝试使用CreateProcess()(带有WINNT的#ifdef),但不确定如何设置相同的命令行。 在Windows上,有没有其他选项可以在C中复制文件而不显示dos窗口?

5个回答

7

Windows提供了CopyFile系列API来实现此功能。


2

这里是我从这个网站上找到的一些代码。你可以将其封装成自己的函数,只需传递源文件和目标文件路径(在此示例中为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;
}

@Jacob 这段代码可以运行,但是我知道 fgetc() 和 fputc() 是非常慢的函数。 - mosg
@Neil:为什么它不会复制空文件? - Jacob
@mosg:是的,如果你可以使用那些API,我建议你使用它们。 - Jacob
@Jacob 对于空文件,第一个feof()测试是没有意义的。然后fgetc()失败,接着ferror()指示了错误,最终程序出错。基本上,谁写这个代码都对feof()的工作原理掌握不好,而且这种方式复制文件非常糟糕。 - anon
@Neil:实际上,fgetc() 不会失败。它返回 ch,使得 int(ch)-1然后 feof(from) 成功防止任何内容被写入目标并退出 while 循环。所以它是有效的,但这是不是一个糟糕的设计呢? - Jacob
1
@Jacob 看起来你关于 ferror 的说法是对的 - 我很久没有使用 C 文件流了。然而,这段代码似乎过于复杂 - 为什么不简单地测试 fgetc() 的返回值呢?并且在出现错误时它没有正确关闭文件,这对于一个独立的程序来说无所谓,但是对于作为其他程序一部分的代码来说会有影响。 - anon

2

我们如何使用ShellExecute()进行复制?没有找到该操作。 - vinaym

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);
    }

以上代码将调用资源管理器的复制处理程序......


0

有一些库可以做到这一点,或者您可以自己编写代码,使用缓冲区和fread/fwrite。我已经很久没有写C代码了,所以无法回忆起确切的语法。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接