Link to home
Start Free TrialLog in
Avatar of oliverUK
oliverUK

asked on

File Copy in C++

I have a file log.txt
how can I copy this file and name it the current date and time?

Thanks
ASKER CERTIFIED SOLUTION
Avatar of cmaryus
cmaryus

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of EarthQuaker
EarthQuaker

If you want to do this using only the standard ( therefore it'll be portable ) :

#include <iostream>
#include <fstream>
#include <algorithm>
#include <string>
#include <ctime>
#include <sstream>

using namespace std;

int main()
{
     time_t rawtime;
     struct tm * info;
     time ( &rawtime );
     info = localtime ( &rawtime );

     stringstream tmp;
     tmp << "File_" << info->tm_mday
          << '-' << info->tm_mon
          << '-' << info->tm_year
          << '_' << info->tm_hour
          << '-' << info->tm_min
          << '-' << info->tm_sec
          << ".log";

     const string strOld = "File.log";
     string strNew = tmp.str();

     copy(istream_iterator<char>( ifstream(strOld.c_str()) ), istream_iterator<char>(), ostream_iterator<char>( ofstream(strNew.c_str()) ));

     return 0;
}

Here's an easier way:


char sTimeDate[26];

struct tm *newtime;
__int64 ltime;

_time64( &ltime );
newtime = _localtime64( &ltime );
strftime( sTimeDateFile, 25, "%b %d %Y, %H:%M.txt", newtime );

CopyFile( "log.txt", sTimeDateFile, false );


For more info on the date/time formatting follow this link:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclib/html/_crt_strftime.2c_.wcsftime.asp