开发者

how to copy files without showing dos window

I have the following code to copy files

sprintf(command, "copy /Y %s开发者_运维百科 %s", sourceFile, targetFile);
system(command);

It works except for the dos window showing up which is very annoying.

I am trying to use CreateProcess() (with an #ifdef for WINNT), but not sure how to setup the command line for the same. Any other options for copying files in C (on windows) without showing dos window?


Windows provides the CopyFile family of APIs for this.


Here's some code I lifted from this website. You can wrap it into your own function and just pass the source and destination file paths (in this example, argv[1] and 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;
}


Use ShellExecute with SW_HIDE http://msdn.microsoft.com/en-us/library/bb762153(VS.85).aspx


There are libraries that can do it, or you can write the code yourself, using a buffer and fread/fwrite. It's been a long time when I last wrote a C code, so I can't recall the exact syntax.


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

The above code will invoke explorer copy handler.....

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜