VB icon

File Copy

Email
Submitted on: 11/4/2016 12:26:03 AM
By: Ben  
Level: Beginner
User Rating: Unrated
Compatibility: C++ (general), Microsoft Visual C++
Views: 916
 
     Copy a file in C++ using fstream with try and catch for error checking. very simple code hope you find it usfull.
 
code:
Can't Copy and Paste this?
Click here for a copy-and-paste friendly version of this code!
				
//**************************************
// Name: File Copy
// Description:Copy a file in C++ using fstream with try and catch for error checking. very simple code hope you find it usfull.
// By: Ben
//**************************************

#include <iostream>
#include <Windows.h>
#include <fstream>
using namespace std;
using std::cout;
using std::endl;
const bool FileExists(string filename){
	//Check if a file was found.
	wstring ws(filename.begin(), filename.end());
	if (GetFileAttributes(ws.c_str()) == INVALID_FILE_ATTRIBUTES){
		return false;
	}
	return true;
}
wstring Str2Wstr(string src){
	wstring ws(src.begin(), src.end());
	return ws;
}
SYSTEMTIME GetFileCreateTime(string Filename){
	wstring ws(Filename.begin(), Filename.end());
	WIN32_FIND_DATAW fd;
	HANDLE f;
	FILETIME ft;
	SYSTEMTIME st;
	//Get the files handle
	f = FindFirstFile(ws.c_str(), &fd);
	if (f == INVALID_HANDLE_VALUE){
		GetLocalTime(&st);
		return st;
	}
	//Store files ftLastWriteTime into ft
	FileTimeToLocalFileTime(&fd.ftLastWriteTime, &ft);
	//Convert ft to system date time.
	FileTimeToSystemTime(&ft, &st);
	//Close close
	FindClose(f);
	//Return the result.
	return st;
}
int main(int argc, char *argv[]){
	ofstream fout;
	ifstream fin;
	char ch = 0;
	char ans = 'N';
	long fAttr = 0;
	SYSTEMTIME st;
	FILETIME ft;
	HANDLE fHandel;
	try{
		if (argc != 3){
			throw std::invalid_argument("Ionnect number of arguments.");
		}
		const string source = argv[1];
		const string dest = argv[2];
		if (source == dest){
			throw std::invalid_argument("Error source and destination cannot be the same.");
		}
		//Check if the dest file exsits.
		if (FileExists(dest)){
			while (1){
				cout << "Overwrite " << dest.c_str() << " (y/n) : ";
				cin >> ans;
				ans = toupper(ans);
				if (ans == 'N'){
					return 0;
				}
				if (ans == 'Y'){
					break;
				}
			}
		}
		//Open source file.
		fin.open(source.c_str(), ios::in | ios::binary);
		if (!fin){
			throw std::exception("Source file not found.");
		}
		fout.open(dest.c_str(), ios::out | ios::binary);
		if (!fout){
			std::exception("Cannot create destination file.");
		}
		//Do the file copy.
		while (fin.get(ch)){
			//Read char
			fout.put(ch);
		}
		if (fin.eof()){
			cout << source.c_str() << " copied to " <<
				dest .c_str()<< " successfully." << endl;
		}
		else{
			throw std::exception("Bsd file copy error.");
		}
		//Close files
		fin.close();
		fout.close();
		//Set the output files attrib with the above.
		st = GetFileCreateTime(source.c_str());
		//Convert system time to file time.
		SystemTimeToFileTime(&st, &ft);
		fHandel = CreateFile(Str2Wstr(dest).c_str(), FILE_WRITE_ATTRIBUTES,
			FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
			fAttr, NULL);
		SetFileTime(fHandel, &ft, &ft, &ft);
		//Close file handel
		CloseHandle(fHandel);
		//Get source file attrib
		fAttr = GetFileAttributes(Str2Wstr(source).c_str());
		//Set file attrib
		if (!SetFileAttributes(Str2Wstr(dest).c_str(), fAttr)){
			throw std::exception("Error setting file attributes.");
		}
		return 0;
	}
	catch (std::exception& e)
	{
		cout << typeid(e).name() << endl << e.what() << endl;
	}
	return 0;
}


Other 50 submission(s) by this author

 


Report Bad Submission
Use this form to tell us if this entry should be deleted (i.e contains no code, is a virus, etc.).
This submission should be removed because:

Your Vote

What do you think of this code (in the Beginner category)?
(The code with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor (See voting log ...)
 

Other User Comments


 There are no comments on this submission.
 

Add Your Feedback
Your feedback will be posted below and an email sent to the author. Please remember that the author was kind enough to share this with you, so any criticisms must be stated politely, or they will be deleted. (For feedback not related to this particular code, please click here instead.)
 

To post feedback, first please login.