You are here:

C++/Rename.Bat - day difference

Advertisement


Question
QUESTION: Good days to you.
I would like to create a batch file (rename.bat), change a file name according to day difference from original.
I hope you can help me for this, thank you.

Example:
On 01 JAN 2013, original file name is A0001.dat
on 02 JAN 2013, need rename to A0002.dat
on 03 JAN 2013, need rename to A0003.dat
and so on...A####.dat

#### is day differance for original file name.

ANSWER: Build this program to generate an executable called "change_file_name.exe":

#include <iostream>
#include <string>
#include <ctime>
#include <sstream>
#include <iomanip>
#include <cstdio>

int main( int argc, char** argv )
{
      if( argc != 2 )
      {
         std::cerr << "usage: " << argv[0] << " <file_to_rename>\n" ;
         return 1 ;
      }

      const char* const file_name_prefix = "A" ;
      const char* const file_name_suffix = ".dat" ;
      const int base_year = 113 ; // 1900 + base_year
      const int MAX_DAYS_PER_YEAR = 366 ;
      const int WIDTH = 5 ;
      const char FILL = '0' ;


      std::time_t now = std::time(0) ;
      const std::tm* ptm = std::localtime(&now) ;
      const int day_number = ptm->tm_yday + ( ptm->tm_year - base_year ) * MAX_DAYS_PER_YEAR ;

      std::ostringstream stm ;
      stm << file_name_prefix
         << std::setw(WIDTH) << std::setfill(FILL) << day_number
         << file_name_suffix ;
      std::string file_name = stm.str() ;

      std::cout << "attempting to rename '" << argv[1] << "' to '" << file_name << "'\n" ;
      if( std::rename( argv[1], file_name.c_str() ) != 0 )
      {
         std::cerr << "*** error *** failed to rename file.\n" ;
         return 2 ;
      }
}

And then, in the batch file, have a line

  change_file_name old_file_name

to rename 'old_file_name' to 'A####.dat'

Note: This is illustrative; this program does not account accurately for leap years.

---------- FOLLOW-UP ----------

QUESTION: == this exe is easy to create by visual basic with datediff function,
however, if you can provide pure bat file will be the best.

Answer
Computation of the dates elapsed using a shell script would also be somewhat verbose.

For several example scripts (Unix), see:
http://www.unix.com/answers-frequently-asked-questions/13785-yesterdays-date-dat

Alas, I'm not at all familiar with the Windows shell.  

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


vijayan

Expertise

my primary areas of interest are generic and template metaprogramming, STL, algorithms, design patterns and c++11. i would not answer questions about gui and web programming.

Experience

about 15 years or so

Education/Credentials
post graduate engineer

©2016 About.com. All rights reserved.