Questions from Beginners MQL5 MT5 MetaTrader 5 - page 1550

 
klycko #:

Unfortunately, your code didn't work for me.

I don't know how to help you.

I checked it again, it works.

#import "kernel32.dll"
bool CopyFileW(string lpExistingFileName, string lpNewFileName, bool bFailIfExists);
#import
//+------------------------------------------------------------------+
void OnStart()// создал файл File.csv в папке Files, скрипт копирует его в папку терминала
  {
   string File = "File.csv";
   string Path = TerminalInfoString(TERMINAL_DATA_PATH);
   string LastPath = Path + "\\MQL5\\Files\\" + File;
   string NewPath = "";

   for(int i = 0; i < 3; i++)
     {
      if(i == 0)
         NewPath = Path + "\\" + File;
      else
         if(i == 1)
            NewPath = LastPath + ".txt";
         else
            NewPath = Path + "\\New" + File;

      bool res = kernel32::CopyFileW(LastPath, NewPath, false);
      Print(res);
     }
  }
//+------------------------------------------------------------------+


As you can see, it copies anywhere and with different names and even with a change of extension.


PS Check for a file, maybe you are confused somewhere.

paste in the beginning of the script

   if(!FileIsExist("File.csv"))
      Print("Пошёл на хе..., нет в папке такого файла!");
 
Aleksandr Slavskii #:

I don't know how to help you.

Checked it again, it's working.


As you can see it copies anywhere and with different names and even with extension change.


PS Check for a file, maybe you are confused somewhere.

paste in the beginning of the script

Thanks for the humour!

I'll check it tonight

 
klycko #:

Thanks for the humour!

I'll check it out tonight

I added your humour to the script and this is what happened:

//+------------------------------------------------------------------+
//|                                                        probb.mq5 |
//|                                  Copyright 2023, MetaQuotes Ltd. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2023, MetaQuotes Ltd."
#property link      "https://www.mql5.com"
#property version   "1.00"

#import "kernel32.dll"
bool CopyFileW(string lpExistingFileName, string lpNewFileName, bool bFailIfExists);
#import
//+------------------------------------------------------------------+
void OnStart()// создал файл File.csv в папке Files, скрипт копирует его в папку терминала
  {
   string File = "File.csv";
   string Path = TerminalInfoString(TERMINAL_DATA_PATH);
   string LastPath = Path + "\\MQL5\\Files\\" + File;
   string NewPath = "";
   
   if(!FileIsExist("File.csv"))
      Print("Пошёл на хе..., нет в папке такого файла!");

   for(int i = 0; i < 3; i++)
     {
      if(i == 0)
         NewPath = Path + "\\" + File;
      else
         if(i == 1)
            NewPath = LastPath + ".txt";
         else
            NewPath = Path + "\\New" + File;

      bool res = kernel32::CopyFileW(LastPath, NewPath, false);
      Print(res);
     }
  }

Although there is a File.csv file in the Files folder, the script doesn't see it and prints:

Fuck off, there is no such file in the folder!

false

false

false



Just fantastic!!!

 

	          
 
klycko #:

Just fantastic!!!

There's no such thing as fantastic.

Make the folder properties visible file extension.

As I see you have a file named File.csv.txt, and you are trying to find File.csv, of course you can't find it.


 

The fiction continues.

I took a sample script from FileCopy documentation.

I supplemented it with your check for file existence.

The result is the same - the script does not see the file.

//+------------------------------------------------------------------+
//|                                                         prob.mq5 |
//|                                  Copyright 2023, MetaQuotes Ltd. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2023, MetaQuotes Ltd."
#property link      "https://www.mql5.com"
#property version   "1.00"
//--- покажем окно входных параметров при запуске скрипта
#property script_show_inputs
//--- входные параметры
input string InpSrc="source.txt";       // источник
input string InpDst="destination.txt";  // копия
input int    InpEncodingType=FILE_ANSI; // ANSI=32 или UNICODE=64
//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
  {
   if(!FileIsExist("InpSrc",0))     // FILE_COMMON
      Print("Нет в папке такого файла!");

//--- отобразим содержимое источника (он должен существовать)
   if(!FileDisplay(InpSrc))                                      //  5004    Ошибка открытия файла
      return;
//--- проверим, существует ли уже файл копии (не обязан быть создан)
   if(!FileDisplay(InpDst))
     {
      //--- файл копии не существует, копирование без флага FILE_REWRITE (правильное копирование)
      if(FileCopy(InpSrc,0,InpDst,0))
         Print("File is copied!");
      else
         Print("File is not copied!");
     }
   else
     {
      //--- файл копии уже существует, попробуем скопировать без флага FILE_REWRITE (неправильное копирование)
      if(FileCopy(InpSrc,0,InpDst,0))
         Print("File is copied!");
      else
         Print("File is not copied!");
      //--- содержимое файла InpDst останется прежним
      FileDisplay(InpDst);
      //--- скопируем еще раз с флагом FILE_REWRITE (правильное копирование при существовании файла)
      if(FileCopy(InpSrc,0,InpDst,FILE_REWRITE))
         Print("File is copied!");
      else
         Print("File is not copied!");
     }
//--- получили копию файла InpSrc
   FileDisplay(InpDst);
  }
//+------------------------------------------------------------------+
//| Чтение содержимого файла                                         |
//+------------------------------------------------------------------+
bool FileDisplay(const string file_name)
  {
//--- сбросим значение ошибки
   ResetLastError();
//--- откроем файл
   int file_handle=FileOpen(file_name,FILE_READ|FILE_TXT|InpEncodingType);
   if(file_handle!=INVALID_HANDLE)
     {
      //--- отобразим в цикле содержимое файла
      Print("+---------------------+");
      PrintFormat("File name = %s",file_name);
      while(!FileIsEnding(file_handle))
         Print(FileReadString(file_handle));
      Print("+---------------------+");
      //--- закроем файл
      FileClose(file_handle);
      return(true);
     }
//--- не удалось открыть файл
   PrintFormat("%s is not opened, error = %d",file_name,GetLastError());
   return(false);
  }
//+------------------------------------------------------------------+
 

Hello, Alexander.

There must be some reason for such behaviour. It is necessary to put forward hypotheses and test them sequentially. For example:

  • Is there a Russian letter ('s' or 'e') in some of the file names? You can take harsher names like "1.bin"
  • Is this the right data directory? Check if it is opened from the terminal menu or MetaEditor.
  • Does the script consider this particular directory as the current one? Add two commands to the beginning of OnStart(): open a new file with creation and close it. See that it appears in the expected directory
I haven't thought of anything else yet
 
klycko #:

The fiction continues.

Onemore time. You need to name a file with the extension of that file.

You have created a file with the extension .txt and the name File.csv

So the full name of the file to be specified in the programme will be File.c sv .txt.

You have disabled display of file extensions in the folder properties in Windows, that's why you have such a confusion with file names.

 
Aleksandr Slavskii #:

There is no fantasy.

Make the file extension visible in the folder properties.

As I see you have a file named File.csv.txt, and you are trying to find File.csv, of course you can't find it.

Thank you very much! That was the problem. Without you I would not have been able to find the error. I wish you success!

 

Alexander, good afternoon!

It turns out that the file must be closed before rewriting it from the sandbox to the Tester folder.

Otherwise it doesn't work.

It took me a long time to figure it out!!!

Regards, Alexander

   string NameSettings = mnth+dy+"-"+LimPos+"-"+DoubleToString(ProfitNew,0)+".set"; // Формируется имя для Settings
   int file_handle=FileOpen("//"+NameSettings,FILE_READ|FILE_WRITE|FILE_CSV|FILE_ANSI);
   FileWriteString(file_handle,Settings+"\r\n");                                    // Записывается строка Settings в песочницу Files
   FileClose(file_handle);                                                          // Закрываем открытый файл, чтобы его можно было дальше перезаписывать

   if(!FileIsExist(NameSettings,0))                                                 // Проверка существования файла
      Print("Нет файла NameSettings!");
   string Path = TerminalInfoString(TERMINAL_DATA_PATH);
   string SrcPath = Path + "\\MQL5\\Files\\" + NameSettings;
   string DstPath = Path + "\\MQL5\\Profiles\\Tester\\" + NameSettings;
   ResetLastError();
   if(!kernel32::CopyFileW(SrcPath,DstPath,false))                                  // Переписываем Settings из песочницы Files в папку Tester
      PrintFormat("Error = %d",GetLastError());    
 
klycko #:

Alexander, good afternoon!

It turns out that the file must be closed before rewriting it from the sandbox to the Tester folder.

Otherwise it doesn't work.

What if it does? ))))

   string NameSettings = mnth+dy+"-"+LimPos+"-"+DoubleToString(ProfitNew,0)+".set"; // Формируется имя для Settings
   int file_handle=FileOpen("//"+NameSettings,FILE_READ|FILE_WRITE|FILE_SHARE_READ|FILE_CSV|FILE_ANSI);
   FileWriteString(file_handle,Settings+"\r\n");                                    // Записывается строка Settings в песочницу Files

   if(!FileIsExist(NameSettings,0))                                                 // Проверка существования файла
      Print("Нет файла NameSettings!");
   string Path = TerminalInfoString(TERMINAL_DATA_PATH);
   string SrcPath = Path + "\\MQL5\\Files\\" + NameSettings;
   string DstPath = Path + "\\MQL5\\Profiles\\Tester\\" + NameSettings;
   ResetLastError();
   if(!kernel32::CopyFileW(SrcPath,DstPath,false))                                  // Переписываем Settings из песочницы Files в папку Tester
      PrintFormat("Error = %d",GetLastError());   
   FileClose(file_handle);                                                          // Закрываем открытый файл, чтобы его можно было дальше перезаписывать
Provided that there is no file with that name in the destination folder.