tags:

views:

113

answers:

4

how to create a system call on c++ that copies one file to the other files?

+1  A: 

There is no yet file-system library in the standard library of C++, so you have several choices :

  • use platform-specific API : you'll use non-portable function specific to your OS but that will do what you want;
  • use a (cross-platform) library : a good library is boost::filesystem but I'm not sure it allows for moving/copying files, just check the functions in the doc;
  • use std::system() to call OS-specific command-line commands : std::system("copy fileA.txt fileB.txt" or similar should work on windows, it's platform specific and can be dangerous from a security point of view, but it works.
Klaim
A: 

This code copies a file in C. You can modify it to copy to a number of files.


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

Blatently stolen from source

Starkey
This example is a perfect reason why you should be writting in C++ not C. The C++ version is only a couple of lines long.
Martin York
A: 

You can use the system function

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

Be carefuly using the "system" function, this is like copying the file from a DOS window, you are basically bypassing Windows.

DevinEllingson
You're assuming this is on Windows. OP didn't specify.
Joe White
It may be a DOS command but still goes throught the OS layer.
Martin York
Joe White - True, it would depend on how the command line interface worked on that platform, but the same code probably woudn't be portable anyway since the command would probably be different.Martin York - True, but using the DOS command line sometimes causes problems especially with delete since you don't get recycle bin support.At any rate I would consider the use of "system" to be a hack, so I would avoid it in general, just my opinion.
DevinEllingson