Working with files . Part I

December 31, 2009
By Bogdan Baltatu, MQLmagazine editor

[Versiunea romaneasca] [MQLmagazine.com in romana] [English edition]

This article will be about working with files and folders in MQL5.

Functions working with files in MQL5 can be divided in two groups:

  • Functions that deal with file manipulation and status of files
  • Functions that deal with reading and writing in files

I will take every function group and describe its functionality with code examples.

Functions that deal with file manipulation and status of files

These functions are the ones that open, close, delete, copy, force writing, check files existance and pointer position within files. These are the functions considered by us in this category :

FileClose, FileCopy, FileDelete, FileFindCLose, FileFindFirst, FileFindNext, FileFlush,
FileIsEnding, FileExist, FileIsLineEnding, FileMove, FileOpen, FileSeek, FileTell

Flags

Part of the function presented above use flags. These flags are global integer constants defined by MQL5 and have the purpose to specify the file opening modes (text,csv,ansi,binary) and the operations done on the file (reading/writing).

The table below contains the binary value but also the integer value of the identifiers, because these are important for understanding how flags work:

Decimal value Binary value Flag identifier Description
1 0000000000001 FILE_READ File open for reading
2 0000000000010 FILE_WRITE File open for writing
4 0000000000100 FILE_BIN Binary access for reading/writing (no strings)
8 0000000001000 FILE_CSV CSV file (Text file with elements separated)
16 0000000010000 FILE_TXT Text file
32 0000000100000 FILE_ANSI ANSI file (one byte symbols)
64 0000001000000 FILE_UNICODE UNICODE file (two byte symbols)
128 0000010000000 FILE_SHARE_READ Acces impartit pentru citire de mai multe programe
256 0000100000000 FILE_SHARE_WRITE Shared access for more programs
512 0001000000000 FILE_REWRITE Possibility to rewrite the file with FileCopy and FileMove.
4096 1000000000000 FILE_COMMON File is in the common folder for all MT5 client terminals

Comparing with the previous MetaQuotes language, MQL4, can be observed the birth of new flags like the ones that give the possibility to open files in new modes like : ANSI, text, UNICODE but also two new modes that allow writing and reading from files even if they are opened by other programs.

A novelty brought by MetaQuotes is opening files that are in MQL5 folder and not only in terminal_directory\experts\files as it was possible in MT4.

Functions working with files may accept flag combinations, but these flags must be used carefully, because for instance you can’t use FILE_TXT|FILE_BIN simultaneously because it’s impossible to open the same file in two modes. I’ll detail the correct flag usage at the FileOpen() function.

FileOpen
The FileOpen() function sits at the base of file operations because there couldn’t be any continuation with other operations if files can’t be created or opened.

1
2
3
4
int FileOpen(string file_name, 
          int open_flags, 
          short delimiter //for CSV files
    );

The function returns an integer (file handle) and this integer has to be memorated in a variable because it will be used with all operations with the file, representing the reference to the opened or created file.

The FileOpen() function has a double role because it is used for both opening and creating files.

1
2
3
4
5
6
7
8
9
int m_handle=-1;
string m_filename="test.txt";
m_handle=FileOpen(m_filename,FILE_READ|FILE_TXT);
if (m_handle<0)
 {
    Print("I can't open the file.");
 } 
else 
  Print("File successfully open.");

The above code opens the test.txt file in the text mode. If the file doesn’t exist, m_handle will remain -1, what means the file hasn’t been open yet. (Surely can’t be opened since it doesn’t exist). If we wish to create a file we have to use FILE_WRITE because the flag is creating the file in the same time. The created file is in the /MQL5/Files/ folder. In the beta version, the one existing now at the time the article is written, the files are not in the MQL5 folder that’s where you installed the platform. To see the exact place where the files are you can use in a script the following line:

1
Print(TerminalInfoString(TERMINAL_DATA_PATH));

Be careful using flags, because wrong use can generate errors.

FileClose

1
2
3
void  FileClose(
   int  file_handle      
   );

The file_handle parameter is the one returned by FileOpen(), in the FileOpen() example the name of our parameter is m_handle. It’s good to reset this parameter to -1 after we close the file if we want to check if the file is still opened. The FileClose() function doesn’t return any result meaning that, at least theoretically the function is successful.

FileDelete

The function deletes a file , be it in the local terminal folder or in the common folder used by all MetaTrader5 platforms.

1
2
3
4
bool  FileDelete(
   string  file_name      // Numele fisierului care va fi sters
   int     common_flag=0  // Flag de localizare
   );

The second parameter is optional. If it is FILE_COMMON then the function will delete the file from the folder that’s shared by all MetaTrader5 platforms; otherwise, it will delete the file from the local station.
The function returns true if the operation was successful, or false in case that it failed.
Functia returneaza true daca operatiunea a fost executata cu succes sau false in caz de operatiunea a esuat.
MetaTrader experts can be run realtime or they can be tested on historical data. When experts are being tested on historical data the functions working with files don’t use MQL5/files anymore, but MQL5/tester instead.

FileCopy
The function copies a folder from the local or common folder to another name keeping the file intact.

1
2
3
4
5
6
bool  FileCopy(
       string  src_filename,       //Name of the file to be copied
       int     common_flag,       //Localization flag
       string  dst_filename,      //Destination file name
       int     mode_flags          //Access flags
   );

The second parameter, common_flag, can’t be missing so when the file we want to copy is not in the MT5 shared folder it has to be replaced with 0.
The mode_flags parameter has two options : FILE_REWRITE and/or FILE_COMMON. If the destination file exists and we try to copy a file without specifying FILE_REWRITE as ‘mode_flags’ parameter then the destination file will not be overwritten by the source.

FileMove
The function’s prototype is the same as FileCopy()’s prototype. The difference is that the FileMove() copies the source file in another location but in the same time deletes the source. Practically the function can be used to rename an existing file.

FileFlush
The function has the role to write on the disc the data from the buffer.

1
2
3
void  FileFlush(
       int  file_handle      
       );

The function has only one parameter, that being the file handle resulted by open/creation with FileOpen().
To understand what FileFlush() is used for, we have to understand how file reading/writing works. When a file is opened the information is copied in memory in a buffer, because memory’s speed is higher than disk speed. A call to FileFlush() is mandatory whenever operation is changed , from reading to writing or the other way around.

FileIsExist
The function FileIsExist checks whether the file exists or not.

1
2
3
4
bool  FileIsExist(
       string  file_name,           
       int     common_flag=0    
       );

The first parameter refers the name of the file, and the second parameter refers the place where the file has to be looked for. The function can be used to limit the errors generated by FileOpen() in the case the file doesn’t exist.

FileTell
The function returns the current position of a file pointer in an open file.

1
2
3
int  FileTell(
       int  file_handle    
       );

The position is in number of bytes from the beginning of the file.

FileIsEnding
The function is used to find out whether the file end has been reached or not.

1
2
3
bool  FileIsEnding(
       int  file_handle      // Handler de fisier
       );

The function is necesary because it’s important to know when the end of the file has been touch, in the most cases when file is read entirely or when we search for something in it.

FileIsLineEnding
The function has the same prototype as the FileIsEnding() function, just this returns true when the end of the line is being touched instead of the end of the file. The function can be used only for text or CSV files and the end of the line is when CR (Carriage Return) or LF(Line Feed) is encountered. However, the function is quite buggy at the time the article is being written.

FileSeek
The function moves the file pointer a specified number of bytes from the specified position.

1
2
3
4
5
void  FileSeek(
       long                 file_handle      
       int                  offset,             
       ENUM_FILE_POSITION   origin  
       );

The origin can be SEEK_SET (begin of the file), SEEK_CUR (current position), SEEK_END (sfarsitul fisierului). The offset can be either positive or negative because the pointer can move in both directions.

The last 3 functions that are presented in this article are FileFindFirst(), FileFindNext() and FileFindClose().

FileFindFirst
The function has the purpose to begin enumerating files in the local or common folder with a specified wildcard.

1
2
3
4
5
long  FileFindFirst(
       string   file_filter,                    
       string&  returned_filename,     
       int      common_flag              
       );

The first parameter is the wildcard.
Wildcard examples :
- “*.*” – all files;
- “*.txt” – text files (to be read “files with a .txt extension”)
- “test.*” – files named test (any extension)
The FileFindFirst() function returns a search handler . The second parameter is the first file that matches the search, and the third parameter is the location flag.

FileFindNext

The function resembles FileFindFirst() , just that the prototype is different:

1
2
3
4
bool  FileFindNext(
       long      search_handle,          
       string&   returned_filename      
   );

The function resumes a previously started search with FileFindFirst() (it knows this from the first parameter, search_handle). The function returns in the second parameter the following file matching the wildcard. It returns true if it fills this parameter with a valid file; if it fails to do that, and this happens at the end of the search, it returns false.

FileFindClose
The function destroys a search handler.
Prototipul functiei este:

1
2
3
void  FileFindClose(
       long  search_handle      
   );

It is necessary use the function in order to release the resources allocated by the call of FileFindFirst().

The function prototypes and even names may be changed by MetaQuotes because at moment this article is written the platform and the MetaEditor are still beta. If you find any mistakes in the article please report.

Leave a Reply