系统调用复制文件

时间:2010-08-05 00:57:02

标签: c++

如何在c ++上创建系统调用,将一个文件复制到其他文件?

4 个答案:

答案 0 :(得分:3)

您可以使用std::system功能

#include <cstdlib>
...
std::system("cp from.txt to.txt");

答案 1 :(得分:1)

C ++标准库中还没有文件系统库,因此您有多种选择:

  • 使用特定于平台的API:您将使用特定于您的操作系统的非便携式功能,但这样做可以满足您的需求;
  • 使用(跨平台)库:一个好的库是boost :: filesystem但我不确定它是否允许移动/复制文件,只需检查文档中的函数;
  • 使用std :: system()来调用特定于操作系统的命令行命令:std :: system(“copy fileA.txt fileB.txt”或类似命令应该适用于Windows,它是特定于平台的,并且可能是危险的安全的观点,但它的工作原理。

答案 2 :(得分:0)

此代码在C中复制文件。您可以修改它以复制到多个文件。


#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
  FILE *from, *to;
  char ch;


  if(argc!=3) {
    printf("Usage: copy  \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;
}

source

中偷偷偷走了

答案 3 :(得分:0)

小心使用“系统”功能,就像从DOS窗口复制文件一样,你基本上绕过了Windows。