Original Post
How could I copy a file from a folder to another one and replace the file if it already exists ? cheers !!
Quote:
Original post by SiCrane
The easy way is to use an operating system specific function like CopyFile() in the Windows API.
Using file streams you can open the source file with an ifstream, then the destination file with an ofstream and stream the input stream's rdbuf into the ofstream.
#include <fstream>#include <string>#include <stdio.h>#include <iostream>using namespace std;//CopyFile is a simple function that copies a file from arg1 to arg2int CopyFile(string initialFilePath, string outputFilePath){ ifstream initialFile(initialFilePath.c_str(), ios::in|ios::binary); ofstream outputFile(outputFilePath.c_str(), ios::out|ios::binary); //defines the size of the buffer initialFile.seekg(0, ios::end); long fileSize = initialFile.tellg(); //Requests the buffer of the predefined size //As long as both the input and output files are open... if(initialFile.is_open() && outputFile.is_open()) { short * buffer = new short[fileSize/2]; //Determine the file's size //Then starts from the beginning initialFile.seekg(0, ios::beg); //Then read enough of the file to fill the buffer initialFile.read((char*)buffer, fileSize); //And then write out all that was read outputFile.write((char*)buffer, fileSize); delete[] buffer; } //If there were any problems with the copying process, let the user know else if(!outputFile.is_open()) { cout<<"I couldn't open "<<outputFilePath<<" for copying!\n"; return 0; } else if(!initialFile.is_open()) { cout<<"I couldn't open "<<initialFilePath<<" for copying!\n"; return 0; } initialFile.close(); outputFile.close(); return 1;}Quote:
Original post by SiCrane
Using file streams you can open the source file with an ifstream, then the destination file with an ofstream and stream the input stream's rdbuf into the ofstream.
Quote:
Original post by jolyqr
ah ah ah. i'm more confused than before...
std::ifstream ifs("input.txt", std::ios::binary);std::ofstream ofs("output.txt", std::ios::binary);ofs << ifs.rdbuf();
#include <stdio.h>#include <stdlib.h>int main(int argc,char *argv[]){ int c; FILE *in,*out; if(argc != 3) { printf("Usage: copy <source> <dest>\n"); } else { in = fopen( argv[1], "r" ); out = fopen( argv[2], "w" ); if(in==NULL || !in) { fprintf(stderr,"%s: No such file or directory\n",argv[1]); return 0; } else if(out==NULL || !out) { fprintf(stderr,"%s: No such file or directory\n",argv[2]); return 0; } while((c=getc(in))!=EOF) putc(c,out); fclose(in); fclose(out); } return 0;}Quote:
Original post by Fruny std::ifstream ifs("input.txt", std::ios::binary);std::ofstream ofs("output.txt", std::ios::binary);ofs << ifs.rdbuf();
This topic has been locked by a moderator. New replies are not allowed.
With your permission, GameDev.net uses analytics cookies to understand how people use the platform. You can accept analytics or continue with necessary cookies only. Learn more