Board index » cppbuilder » Renaming lots of files

Renaming lots of files


2007-01-20 06:29:08 AM
cppbuilder14
Can someone please offer me some assistance with the following?
I have a bunch of files with the naming convention of
Monday January 01, 1955.txt
Wednesday March 27, 1910.txt
etc. etc.
I have to parse through the directories, and the sub-dirs looking for the text files. When I find them, I have to rename each file into the following format.
year,month,day.txt
I.e
19100427.txt
19550101.txt
I really don't know how to start this, if someone can give me a head start, 9 am sure I can finish.
Thanks
Joel
 
 

Re:Renaming lots of files

Most tasks are too complex to be handled in one lump. One must subdivide
them.
Start by pretending that you know how to do all of the job. Block out what
tasks are needed.
For example, selecting a directory in which to search, searching for files,
determining that a file that was found is one you wish to handle,
constructing the new name, renaming, reporting progress to the screen. Once
you have the definition of the individual tasks that will be used, you can
write stubs for each and then for each, examine the task, decide how to
actually do it and put code for that into the stub.
If I were doing this I'd probably create a class or classes for searching
for *.txt files and another to handle the file names.
. Ed
Quote
Joel Keens wrote in message
news:45b14634$ XXXX@XXXXX.COM ...

Can someone please offer me some assistance with the following?

I have a bunch of files with the naming convention of

Monday January 01, 1955.txt
Wednesday March 27, 1910.txt

etc. etc.

I have to parse through the directories, and the sub-dirs looking
for the text files. When I find them, I have to rename each file
into the following format.

year,month,day.txt

I.e

19100427.txt

19550101.txt

I really don't know how to start this, if someone can give me
a head start, 9 am sure I can finish.
 

Re:Renaming lots of files

Hay Joel, Ed's comments are spot on - break the task down into workable
parts and construct little 'proof-of-concepts' for each one.
However, I get the feeling your looking for something more code related, so
here's a few pointers to get you started. The task that you are trying to
do, file-search is a classic example of recursion. Recursion is basically
when a function call's it's self, over and over again. The basic idea is
that you write a generic search function and when ever it finds a directory,
it calls it's self again, to search that directly, and so on and so forth.
It can get a bit confusing and is proven to causing unexpected error because
of this confusion. I'm pretty sure there are some examples of File Explorer
style application in the BCB Examples directory and I seem to recall that
one of these has a recursive function in it.
However, make sure that your recursion works without error before you start
renaming or you could end up with big problems.
The FindFirst, FindNext wrappers will allow you to search for files in a
particular directory and the RenameFile to deal with changing the file name.
RenameFile will accept an AnsiString so it is pretty easy to construct your
file - also look at the FormatDateTime function - I use this to construct
file names in a similar fashion.
A quick Google search chucked up this article - in Delphi - but the concepts
is exactly the same:
delphi.about.com/od/vclusing/a/findfile.htm
"Joel Keens" < XXXX@XXXXX.COM >wrote in message
Quote

Can someone please offer me some assistance with the following?

I have a bunch of files with the naming convention of

Monday January 01, 1955.txt
Wednesday March 27, 1910.txt

etc. etc.

I have to parse through the directories, and the sub-dirs looking for the
text files. When I find them, I have to rename each file into the
following format.

year,month,day.txt

I.e

19100427.txt

19550101.txt

I really don't know how to start this, if someone can give me a head
start, 9 am sure I can finish.

Thanks
Joel

 

{smallsort}

Re:Renaming lots of files

Hello Joel,
It is not clear to me after reading your question and the responses
so far if your are addressing a current task or if you are trying
to construct a tool for doing so?
My general assumption is the prior not the later.
If so, then here is my two cents worth. I used to consider this sort
of task a high art...
My general approach would typically reduce hours of mind numbing, error
prone unmitigated tedium down to less than a hour.
Get yourself a copy of the console program SED (StreamEDitor). It is
ubiquitous. Combining a quickly created SED script with a batch file
will fully automate a task such as this in short order.
I offer this advice in the context that this sort of task is likely to
reoccur. If you don't expect to do anything like this again anytime soon
then you probably can't justify the time to learn to write SED scripts
though. If on the other hand you expect to much of this stuff. Check it
out.
HTH,
Bruce Larrabee
 

Re:Renaming lots of files

Try something line this /totally untested/:
(I'll add the code to the attachments group also)
--- CPP ---
//---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include <Filectrl.hpp>
#include "Unit1.h"
#include <stdio.h>
#include <fcntl.h>
#include <io.h>
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
Edit1->Text = ExtractFilePath( ParamStr(0) );
}
// Select root folder
void __fastcall TForm1::Button2Click(TObject *Sender)
{
AnsiString Dir = Edit1->Text;
if ( !SelectDirectory( Dir, TSelectDirOpts() << sdAllowCreate <<
sdPerformCreate << sdPrompt, 0 ) )
return;
Edit1->Text = IncludeTrailingBackslash( Dir );
}
// Go
void __fastcall TForm1::Button1Click(TObject *Sender)
{
Button1->Enabled = false;
try
{
ListView1->Items->Clear();
AnsiString Dir = Edit1->Text;
if ( ! DirectoryExists( Edit1->Text ) )
{
ShowMessage( "Folder does not exist!" );
return;
}
Pass = 0;
FindFilesInDirectory ( Dir );
Pass = 1;
FindFilesInDirectory ( Dir );
}
__finally
{
Button1->Enabled = true;
}
}
// Recursion
void TForm1::FindFilesInDirectory (const AnsiString &Dir )
{
if ( Pass == 0 )
FindExtension ( Dir, "*.txt" );
if ( Pass == 1 )
FindExtension ( Dir, "*.~txt" );
WIN32_FIND_DATA filedata;
HANDLE filehandle;
String dir = Dir + "*.*" ;
filehandle = FindFirstFile ( ( Dir + "*.*" ).c_str (), &filedata );
if ( filehandle != INVALID_HANDLE_VALUE )
{
do
{
if ( ( filedata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) != 0
&& String (filedata.cFileName) != "."
&& String (filedata.cFileName) != ".." )
{
FindFilesInDirectory ( Dir + filedata.cFileName + "\\" );
}
Application->ProcessMessages () ;
} while ( FindNextFile ( filehandle, &filedata ) ) ;
FindClose ( filehandle ) ;
}
Application->ProcessMessages() ;
}
void TForm1::FindExtension ( const AnsiString &Path, const AnsiString &Ext )
{
WIN32_FIND_DATA filedata;
HANDLE filehandle ;
filehandle = FindFirstFile ( ( Path + Ext ).c_str(), &filedata ) ;
if ( filehandle != INVALID_HANDLE_VALUE )
{
int Succ;
AnsiString Result = "";
do
{
TListItem *li = ListView1->Items->Add();
AnsiString FullFileName = Path + filedata.cFileName;
li->Caption = ExtractFileName( FullFileName );
if ( filedata.nFileSizeHigh == 0 )
{
li->SubItems->Add ( AnsiString ( (int) ( ( filedata.nFileSizeLow
+ 1023 ) / 1024 ) ) + " K" );
}
else
{
double filesize = ( MAXDWORD * filedata.nFileSizeHigh ) +
filedata.nFileSizeLow;
li->SubItems->Add ( String ( filesize / 1024.0 ) + " K" );
}
switch ( Pass )
{
case 0: li->SubItems->Add ( "Changing+Renaming: *.txt" );
break;
case 1: li->SubItems->Add ( "Renaming: *.~txt ->*.txt" );
break;
default: li->SubItems->Add ( "WTF!" );
break;
}
Succ = GoParseFileName( FullFileName );
Result = "N/A";
switch ( Succ )
{
/*
case 0: Result = "Successful!";
break;
case 1: Result = "Could not rename to a new file name";
break;
case 2: Result = "Could not rename new file name to *.~txt";
break;
case 3: Result = "Could not rename new file name to *.txt";
break;
*/
}
li->SubItems->Add ( Result ) ;
Application->ProcessMessages () ;
} while ( FindNextFile ( filehandle, &filedata ) ) ;
FindClose (filehandle) ;
}
}
int TForm1::GoParseFileName( AnsiString FN )
{
if ( Pass == 0 )
{
AnsiString NewFileName = GiveMeNewFileName( FN );
if ( ! RenameFile( FN, NewFileName ) )
return ( 1 );
if ( ! RenameFile( NewFileName, ChangeFileExt( NewFileName,
".~txt" ) ) )
return ( 2 );
return ( 0 );
}
if ( Pass == 1 )
{
if ( ! RenameFile( FN, ChangeFileExt( FN, ".txt" ) ) )
return ( 2 );
return ( 0 );
}
}
AnsiString TForm1::GiveMeNewFileName( const AnsiString &AFileName )
{
// Expected:
// Monday January 01, 1955.txt
// Wednesday March 27, 1910.txt
AnsiString FN = ExtractFileName( AFileName );
AnsiString FP = ExtractFilePath( AFileName );
AnsiString Year = FN.SubString( FN.Pos( "." )-4, 4 );
AnsiString Day = FN.SubString( FN.Pos( "," )-2, 2 );
// English is not my native language... Please check if I typed correctly
AnsiString Months[12] = { "January", "February", "March", "April", "May",
"June", "July", "August", "September", "October", "November", "December" };
AnsiString Month;
for ( int i=0; i<12; i++ )
{
if ( FN.Pos( Months[i] )>0 )
{
Month = AnsiString( i+1 );
break;
}
}
if ( Month.Length() == 1 )
Month = "0" + Month;
return ( FP + Year + Month + Day + ".txt" );
}
--- H ---
//---------------------------------------------------------------------------
#ifndef Unit1H
#define Unit1H
//---------------------------------------------------------------------------
#include <Classes.hpp>
#include <Controls.hpp>
#include <StdCtrls.hpp>
#include <Forms.hpp>
#include <ComCtrls.hpp>
#include <Grids.hpp>
#include <ExtCtrls.hpp>
//---------------------------------------------------------------------------
class TForm1 : public TForm
{
__published: // IDE-managed Components
TButton *Button1;
TButton *Button2;
TEdit *Edit1;
TPanel *TitlePanel;
TLabel *IzaberiteLabel;
TListView *ListView1;
void __fastcall Button1Click(TObject *Sender);
void __fastcall Button2Click(TObject *Sender);
private: // Repository headers declarations
int Pass;
void FindExtension (const AnsiString&, const AnsiString&);
void FindFilesInDirectory (const AnsiString& );
int GoParseFileName( AnsiString );
AnsiString GiveMeNewFileName( const AnsiString& );
public: // Repository headers declarations
__fastcall TForm1(TComponent* Owner);
};
//---------------------------------------------------------------------------
extern PACKAGE TForm1 *Form1;
//---------------------------------------------------------------------------
#endif
--
Best Regards,
Vladimir Stefanovic
 

Re:Renaming lots of files

"Vladimir Stefanovic" < XXXX@XXXXX.COM >wrote:
Quote

Check out bpot.
~ JD
 

Re:Renaming lots of files

Quote
Check out bpot.
Rudy's demonstrating his 'power' again ;)
I'll check out more deeply on monday. I'll be absent whole day today...
--
Best Regards,
Vladimir Stefanovic
 

Re:Renaming lots of files

"Vladimir Stefanovic" < XXXX@XXXXX.COM >wrote:
Quote
>Check out bpot.

Rudy's demonstrating his 'power' again ;)

I'll check out more deeply on monday. I'll be absent whole day today...
Too late (unless they've been archived). Have a look in
Borland.Canceled.
~ JD