system call to copy files [closed]
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this questionhow to create a system call on c++ that copies one file to the other files?
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.
You can use the std::system function
#include <cstdlib>
...
std::system("cp from.txt to.txt");
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
Be carefuly using the "system" function, this is like copying the file from a DOS window, you are basically bypassing Windows.
加载中,请稍侯......
精彩评论