How to delete files in specified folder?

Does help say anything about wildcards: http://www.amibroker.com/guide/afl/fdelete.html ?

fdelete() is a direct call to Windows DeleteFile. As name says it deletes a file (single, not plural form)

If you need to delete all files in a directory you need to use fdir() to get folder content, iterate and delete one by one.

There is even ready-to-use code in the User’s Manual: http://www.amibroker.com/guide/afl/fdir.html
but WHY lookup the manual, it would be too much of effort, wouldn’t it be ?

Dear Sir
I have try using single backslash like the guide link, but error 54 occurs, so I change to double backslash instead, correct ?

and try to code the rest.

thanks

rgds bob

I try to code using fdir, as the guid from the link and add fdelete files, it cannot delete file, and I debug to what happens are in both using watch window and output window :

printf( "Only files: " ); 
_N( list = fdir( "c:\\AmiBackupD\\*.*", 1 ) ); 
printf( " Both files and directories: " ); 
_N( list = fdir( "c:\\AmiBackupD\\*.*", 3 ) ); 
for ( i = 0; ( filename = StrExtract( List, i ) ) != ""; i++ ) 
{ 
    printf( filename + " " ); 
    fdelete(filename);
    wait=0;
}

there are only three files in the folder of c:\AmiBackupD :slight_smile:

and watch the result from the watch output window to see every loop running :

the first Loop :

the second loop :

the third loop :

the fourth loop :

the fifth loop :

so I cannot delete the file, because the filename have no contain directory name, and I have try to put the code like this : "C:\AmiBackupD\" or "C:\AmiBackupD" in variable, also fail.

so, how to solve this kind of problem.

Thanks

RGDS bob

Your loop just lists file names but in order to make your fdelete command to work you need to add the actual path to those files! It’s like giving someone a list of goods to buy but you don’t tell him/her the actual route to get it from. So if you give AmiBroker just a few names to delete then it will search in its installation folder “…\AmiBroker\” only. But since nothing is there and your actual “goods store” is somewhere else nothing will happen.

So here again another user error. Nothing more nothing less.

printf( "Only files: " );

dir = "C:\\AmiBackupD\\";
 
_N( list = fdir( dir + "*.*", 1 ) ); 

for ( i = 0; ( filename = StrExtract( List, i ) ) != ""; i++ ) 
{ 
    printf( filename + "\n" ); 
    fdelete(dir + filename);// path AND file
}

Read carefully here https://www.amibroker.com/guide/afl/fdelete.html

1 Like

One of my favorites, to delete a folder containing ten of thousand files, as quick as possible and without use of the “Recycle Bin” is shift+Delete on the folder itself, with the keyboard.

I wonder if there is a code version to do this, or one as fast or faster. FYI, I hate having to delete each file one by one.

@Sean, how long have you been using AmiBroker? AFAIR, multiple years already. So you have never explored the AmiBroker functions list? Really?

https://www.amibroker.com/guide/AFL.html
https://www.amibroker.com/guide/a_funref.html

Either use

dir = "C:\\Folder\\";

if ( ParamTrigger( "Delete directory", "CLICK HERE" ) )
{   
    /// @link https://www.amibroker.com/guide/afl/frmdir.html
    frmdir( dir );
}

Or

dir = "C:\\Folder\\";

if ( ParamTrigger( "Delete directory", "CLICK HERE" ) )
{   
     /// removes empty or non-empty directory incl. subdirectories
     /// @link http://forum.amibroker.com/t/how-to-delete-files-in-specified-folder/1327/5
     ShellExecute( "cmd", "/c rmdir " + dir + " /s /q", "", 0 );
}
2 Likes

lol, I don’t have those to memory.

I was just trying to mention a another possible place to look and in a different direction. If let’s say you wanted all the files deleted in the directory. Perhaps then the best way might be to delete the folder then create it again, the fastest way possible etc.

I know many are familiar doing the heavy lifting with, as an example the Directory Info and File Info Classes in C#; making a list of all files, loop them to delete each file and then finally delete the Directory once it is empty. That’s a lot of code, just wipe out a directory etc. But then again maybe that or something similar is what is happening in the code executed by “Shift + Delete” :roll_eyes:

I just made a comment because it looked like the AFL code was doing it similarly.
-S

Dear All
Thanks to Mr Tomasz and Fxshrat give me the clue and information for solving my coding problem, also thanks Amibroker provide the forum to help us to solve all kind of problem and share to others around the world to learn also.

now AFL run well, and Fxshart add another commond for ShellExecute that what I’m also looking for, but I don’t know what is the function name, so all your help will improve my programming knowledge.

for Sean, what I want to do actualy is the AFL of export Data into CSV file, before export, I must delete all the data that remain in the folder that contain data, so I write the delete file prior to Export coding, that’s my reason.

Sorry for late reply and my poor English!

thaks.

rgds Bob Tanujaya (Indonesia)

Dear sir
I have a problem, difficult to explain, so I put the code and the flowchart.

I have finish coding AFL as 1st module to empty all stock at specific folder and coding another AFL as 2nd module to export all symbol at the same specific folder.

//-------------first module to empty all the data inside C:\AmibrokerD-------
dir = "c:\\AmiBackupD\\";
CheckMakeDirectory=fmkdir(dir);	
if(CheckMakeDirectory==0) // jika ada directory c:\\AmiBackupD
{
	_N( list = fdir( dir + "*.*", 1 ) ); 
	for ( i = 0; ( filename = StrExtract( List, i ) ) != ""; i++ ) 
	{ 
		CheckDeleteFile = fdelete(dir + filename);// path AND file
	}
	frmdir(dir);
}

//------------second module, export data convert to CSV and put in the c:\AmibrokerD-----
fmkdir(dir);
fh = fopen( dir +Name()+".TXT", "w"); 
if( fh ) 
{ 
	fputs( "Ticker,Date,Open,High,Low,Close,Volume \n", fh ); 
	y = Year(); m = Month(); d = Day(); //r = Hour();e = Minute();n = Second();
	for( i = 0; i < BarCount; i++ ) 
	{ 
		fputs( Name() + "," , fh );
		ds = StrFormat("%02.0f-%02.0f-%02.0f,", y[ i ], m[ i ], d[ i ] ); 
		fputs( ds, fh ); 

		qs = StrFormat("%.4f,%.4f,%.4f,%.4f,%.0f\n", O[ i ],H[ i ],L[ i ],C[ i ],V[ i ] ); 
		fputs( qs, fh ); 
	} 
	fclose( fh ); 
} 
Buy = 0;

after finish test the 1st module and 2nd module separately, and try to make the new AFL let say 3rd AFL which combining from these two 1st module and 2nd module.

so every 1st module and 2nd module running itself module alone and run well, but when combine two AFL into on AFL(3rd AFL), I found that the 1st module after emptying all data in the folder and continue to export all data into the same folder (2nd module), and something wrong happen, because the result inside the folder consist only few files, so I realize that its looping all the 1st and 2nd all the time, so after export one symbol, and go to the top run the empty AFL (1st AFL) and continue run the 2nd modul (export data), and go on again and again, until all the data export, so the result is on only few files that have not been delete.

so, how do I declare a something like switch to switch off, and after running empty files to set the switch on, continue export data to folder, looping into beginning and will skip 1st modul and directly go to the 2nd module continue to export the next symbol, and continue go to top and skip the 1st module and directly go to the 2nd module continue to export the next symbol, and go on again and again until finish export all the symbol ?

I don’t know how to coding like that, I don’t know how to define a kind of glabal memory as a switch, and will maintain to prevent the empty module and directly export the symbol

to make it clear, I draw the flowchart like picture below :slight_smile:

So sorry for my poor english,

Some one will Help me to solve this kind of problem ?

thaks for help

rgds bob tanujaya

You can use Static variable for this. Use StaticVarGet to read the variable and StaticVarSet to store your desired value. In your code, you can check the value of the variable before you set it. On first run, the variable will not have the value set by you. On second run, the static variable will have value set by you.

There is one more way. If you are ok to handle it manually, add a ParamToggle. Check the value of the param used and decide the flow accordingly.

@yenpok i dont know why you open another post?
Tomasz and fxshrat are allready answer. And you thanks that post.

i think you have to go back and read again for ParamTrigger() at post 7

and Be Careful when you Delete files and folders. :thinking:

Moderator comment: @PanoS is right. There is no need to create new topics to continue old story. It has been moved to old topic.

Hi Pano S,
I think the delete specified folder Questions have been answered and resolved the problem.
so this time I just don’t know how to set the 1st module (delete file) just only run one time / first time, and don’t want to run the second time, so after finish delete file start to run the 2nd module to export data, that’s why I thiks is diffrent topic, so I start the new topic.

and I am learning to write afl codie, so I want to automatic for one’s click will do all the task, the reason is learning programming improve my skill and make me handy to export data.

thanks
tgds bob

Dear Aniruddhakhopkar
Sorry for lately answer your respond, because my internet down for four days, and I have try using static variable, but fail.
this my coding, I don’t know what is wrong, I don’t use to use the staticVar, is there something wrong ? please help to solve this problem or give me a clue/ link for me to study with

code :

//-------------first module to empty all the data inside C:\AmibrokerD-------
dir = "c:\\AmiBackupD\\";

function DeleteFile() {
	CheckMakeDirectory=fmkdir(dir);	
	if(CheckMakeDirectory==0) 	{
		_N( list = fdir( dir + "*.*", 1 ) ); 
		for ( i = 0; ( filename = StrExtract( List, i ) ) != ""; i++ ) 		{ 
			CheckDeleteFile = fdelete(dir + filename);// path AND file
			a=0;
		}
	}
	else 	{
		fmkdir(dir);
	}
}

function ExportData() {
	fh = fopen( dir +Name()+".TXT", "w"); 
	if( fh ) { 
		fputs( "Ticker,Date,Open,High,Low,Close,Volume \n", fh ); 
		y = Year(); m = Month(); d = Day(); //r = Hour();e = Minute();n = Second();
		
		for( i = 0; i < BarCount; i++ )	{ 
			fputs( Name() + "," , fh );
			ds = StrFormat("%02.0f-%02.0f-%02.0f,", y[ i ], m[ i ], d[ i ] ); 
			fputs( ds, fh ); 

			qs = StrFormat("%.4f,%.4f,%.4f,%.4f,%.0f\n", O[ i ],H[ i ],L[ i ],C[ i ],V[ i ] ); 
			fputs( qs, fh ); 
		} 
		fclose( fh ); 
	} 
}

//------------main program-----------
StaticVarRemove("var1");
Nz(StaticVarGet("var1"),0);
var1=staticvarget("var1");  // for debug variable var
if(var1==0)
//if(IsNull(var1))
{
	deletefile();
	StaticVarSet("var1",1);
	var1=staticvarget("var1"); // for debug variable var
}
else
{
	StaticVarSet("var1",1);
	var1=staticvarget("var1");  // for debug variable var
	ExportData();
}
Buy=1;

thanks a lot

RGDS Bob Tanujaya

Hello @yenpok
Here is a code that use StaticVar, please read the comments
tested and working for me

the story of the code is :

  1. Nz( StaticVarGet( “var1” ), 0 ); Converts to Zero - from Emtpy.
  2. DeleteFiles() -ONCE - before you run exploration
  3. StaticVarSet( “var1”,1 ); began true after you hit explore or scan
/// @link http://forum.amibroker.com/t/how-to-delete-files-in-specified-folder/1327/14

dir = "R:\\AmiBackupD\\"; // fmkdir( dir );
var1= Nz( StaticVarGet( "var1" ), 0 );  Converts Null/Nan/Infinity values to zero (or user defined value)

function DeleteFiles()
{
	if (var1==0)
	{
    _N( list = fdir( dir + "*.*", 1 ) );
    for( i = 0; ( filename = StrExtract( List, i ) ) != ""; i++ )
    {
        printf( filename + "\n" );
        fdelete( dir + filename ); // path AND file
    }
    }
    fmkdir( dir );
}

DeleteFiles();  // delete Files in Directory ONCE (as we use StaticVar Inside the Exploration Code)


//  below Code run ONLY in Exploration or Scan mode
if( Status( "Action" ) == actionScan OR Status( "Action" ) == actionExplore )
{
    	StaticVarSet( "var1",1 );
    	_TRACE("#,EXP end = " + var1 + " ticker, "+Name());  //for debuging


// Now exportExportData
    fh = fopen( dir + Name() + ".TXT", "w" );

    if( fh )
    {
        fputs( "Ticker,Date,Open,High,Low,Close,Volume \n", fh );
        y = Year();
        m = Month();
        d = Day(); //r = Hour();e = Minute();n = Second();

        for( i = 0; i < BarCount; i++ )
        {
            fputs( Name() + "," , fh );
            ds = StrFormat( "%02.0f-%02.0f-%02.0f,", y[ i ], m[ i ], d[ i ] );
            fputs( ds, fh );

            qs = StrFormat( "%.4f,%.4f,%.4f,%.4f,%.0f\n", O[ i ], H[ i ], L[ i ], C[ i ], V[ i ] );
            fputs( qs, fh );
        }
        fclose( fh );
    }
    Buy = 1;
}
  
  

Hi PanoS

it take a long time for me to learn the static variable :slight_smile:
I try to understand the Static Variable, but I have a trouble to understand it, please check the pictures below,

  1. I use the debuging to get the variable var2 from var1 and make sure the var1 = Null

  1. use Nz function convert var1 from Null to zero, and check the variable "check" found that it's fail. (check = 0)

  2. get and check what is inside var1 using StaticVariableGet, the result still Null

so I fail to make var1 from Null to 0,
please show me the where the erros are.

thanks
Rgds Bob Tanujaya

hello
Your code is wrong,

// correct is 
Var2 = StaticVarGet( "ThisIsUniqueText" );
check = Nz( var2, 0 );

Hello
Thanks you. This is nice question.
To be honest my mind goes in 3 different thinks now.
So I am guessing that you export your data ONCE per day.
So NEXT DAY your folder has left over files from yesterday, and after run exploration you empty the folder to write the new ones.
Actually, you donot have to delete the files as after exploration files are overwritten.

Any way. Let’s go to your Study Question
Here is little bit more code for exercise

// exercise code for study
// please, OPEN THE INTERPRITATION WINDOW to read the outputs
  
var = StaticVarGet( "TestVar" );
check = Nz( var, 0 );
varZero = Nz( StaticVarGet( "TestVar" ), 0 ); 
varSeven = Nz( StaticVarGet( "TestVar" ), 7 );


"\n Note that NZ() Converts Null/Nan/Infinity values to zero (or user defined value) ";
printf( "\n Check is  \t" + check);
printf("\n var  = %g,\t \n varZero  = %g,\t \n varSeven = %g\n", var, varZero , varSeven );

"\n So all avobe are NOT use the StaticVarSet() yet ";
"\n --------------------------";


"\n Please uncomment line below to SET a number 20 to the Static Variable TestVar";
// StaticVarset( "TestVar" ,20);


if( varZero == 20 )
{
    printf( "\n\n varZero Now is equal to = \t" + varZero );
}
else 
printf( "\n TestVar is  \t" + var);


// uncomment below line ONLY TO RESET the StaticVars JUST for testing then comment again
// StaticVarRemove("TestVar");

Later on, go to the link that use again statickvar for more study

https://www.amibroker.com/guide/afl/say.html

thanks Panos.

I try my best to learn static variable thank very much on your guidance and help that are very useful for me as a beginner to learn better amibroker.

rgds bob tanujaya

Dear Panos,

You said that :

that’s right what I want to do, and from that I can improve and learn more programming skill, because I am affraid that cannot wipe out all remain data, so I must delete all data first and then do the export data.

anyway, I will learning AFL better.

thanks

rgds bob

Dear Pano SDear Pano S
it took a long fime for me to study and understand staticVar, and finally back to your coding, and make sure to add StaticVarRemove at the end of coding, and everything is run well. if I don’t add the StaticVarRemove, run the first time is ok, but the second time and etc will not prior delete the files, that cause me always fail before understand what StaticVar’s are.

the one more thing I don’t know that if I run in the debug mode, cannot simulated with what running in the actionScan or actionExplore?

before I just tracing from the debug mode, always fail in looping the export file through all symbol, after try running from the scan or explore mode, everything run normal, although I get trouble without add StaticVarRemove function

the complete code :

dir = "C:\\AmiBackupD\\"; // fmkdir( dir );
var1= Nz( StaticVarGet( "var1" ), 0 );  //Converts Null/Nan/Infinity values to zero (or user defined value)

function DeleteFiles()
{
	if (var1==0)
	{
		_N( list = fdir( dir + "*.*", 1 ) );
		for( i = 0; ( filename = StrExtract( List, i ) ) != ""; i++ )
		{
			printf( filename + "\n" );
			fdelete( dir + filename ); // path AND file
		}
    }
    fmkdir( dir );
}
printf("\n var1 is\t" + var1 + "\n");
DeleteFiles();  // delete Files in Directory ONCE (as we use StaticVar Inside the Exploration Code)


//  below Code run ONLY in Exploration or Scan mode
if( Status( "Action" ) == actionScan OR Status( "Action" ) == actionExplore )
{
    StaticVarSet( "var1",1 );
    //_TRACE("#,EXP end = " + var1 + " ticker, "+Name());  //for debuging
	var1 = StaticVarGet("var1");
	var1String = NumToStr(var1,1.0);
	// Now exportExportData
    fh = fopen( dir + Name() + ".TXT", "w" );

    if( fh )
    {
        fputs( "Ticker,Date,Open,High,Low,Close,Volume \n", fh );
        y = Year();
        m = Month();
        d = Day(); //r = Hour();e = Minute();n = Second();

        for( i = 0; i < BarCount; i++ )
        {
            fputs( Name() + "," , fh );
            ds = StrFormat( "%02.0f-%02.0f-%02.0f,", y[ i ], m[ i ], d[ i ] );
            fputs( ds, fh );

            qs = StrFormat( "%.4f,%.4f,%.4f,%.4f,%.0f\n", O[ i ], H[ i ], L[ i ], C[ i ], V[ i ] );
            fputs( qs, fh );
            printf( "var1String = "+var1String +"\t" + ds + "\t" + qs);
        }
        fclose( fh );
    }
    Buy = 1;
}
StaticVarRemove("var1");

now everything is solve.
thanks for Pano S teach me the valuable lesson.

RGDS bob Tanujaya