简体   繁体   中英

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为此提供了CopyFile系列API。

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

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.....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM