Writing to the file on a new line

 

Help me figure out how to write to a file.

Here's the function:

if(DayOfWeek()==day){ //Print("Woking . . .");
  ac=Symbol(); 
  ss1 = ac+day+";"+TimeToStr(TimeCurrent(),TIME_MINUTES)+";"+DoubleToStr(AccountBalance(),1)+";"+DoubleToStr(AccountEquity(),1)+"\n";
   WriteFile (path, ss1);
   day++;if(day==6)day=1;
}

........


//+------------------------------------------------------------------+
void WriteFile(string path,string buffer){
int count=StringLen(buffer),result,handle=_lopen(path,1); 
if(handle<0){ handle=_lcreat(path,0);
if(handle<0){ Print ("Ошибка создания файла ",path);return;}
result = _lclose (handle); }
handle=_lopen (path,1);if(handle<0){Print("Ошибка открытия файла ",path);return;}
result=_llseek(handle,0,0);if(result<0) {Print("Ошибка установки указателя"); return; }
buffer = buffer + "\n";
result=_lwrite(handle,buffer,count); if(result<0)Print("Ошибка записи в файл ",path," ",count," байт");
//result=_lclose (handle); if(result<0)Print("Ошибка закрытия файла ",path);
  }

I need new data to be written on a new line in Excell, I've looked through all the code on the forum, including the tutorial and documentation, but no result :(((
 

I use Kim's function - open file - write a line - close the file and then go around.

//+------------------------------------------------------------------+
//| Запись строки в файл                                             |
//+------------------------------------------------------------------+
void WritingLineInFile(string FileName, string text)
{
  int file_handle=FileOpen(FileName, FILE_READ|FILE_WRITE, " ");

        if (file_handle>0)
        {
                FileSeek(file_handle, 0, SEEK_END);
                FileWrite(file_handle, text);
                FileClose(file_handle);
        }
}
 

live editing...

 

Thanks, it worked.

I also ran Kim's, but the string was different handle = FileOpen("Summa.txt", FILE_CSV|FILE_WRITE, '\t');

 
Donatom:

I use Kim's function - open file - write string - close file and then around.


do not want to check, but I think FileFlush() https://docs.mql4.com/ru/files/FileFlush should help not to close the file every time, if FileFlush() fixes the situation, it is better to open the file in init(), and close in deinit(), I did something similar, it seems adding once again FileWrite(file_handle, ""); will write a new line - that is, every FileWrite() is written with a new line - check it

ZS: I always write non-standard offline graphics without closing them, using FileFlush()

 
int FileWriteArray( int handle, objectarray[], int start, int count)
The function writes an array to a binary file. Int, bool, datetime and colour arrays are written as 4-byte integers. Arrays of type double are written as 8-byte floating-point numbers. String arrays are written line by line, with an end-of-line sign "\r\n" automatically added after each line.

delimiter - Delimiter character for csv files. By default ';' is used.
i.e. DO NOT insert them
S)+";"+Do

You can also make an empty array :) of 1 or 2 elements :) or add...
+DoubleToStr(AccountEquity(),1)+"\r\n";
      
FileWrite(path, Symbol(), TimeToStr(TimeCurrent(),TIME_DATE),DoubleToStr(AccountBalance(),1), DoubleToStr(AccountEquity(),1),TimeToStr(TimeCurrent(),TIME_SECONDS)+"\r\n");

 

Hi all. I am trying to write each new order in a new line, could you tell me what I am doing wrong? Only the last open order remains.

void OnTick()

{
int i, type;
double lot=0,sl=0,tp=0;
for(i=0; i<OrdersTotal(); i++)
{
if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
{
if(OrderSymbol()==Symbol())
{
if(OrderType()==OP_BUY)
{
type=0;
lot=OrderLots();
sl=OrderStopLoss();
tp=OrderTakeProfit();
}
if(OrderType()==OP_SELL)
{
type=1;
lot=OrderLots();
sl=OrderStopLoss();
tp=OrderTakeProfit();
}
}
}
}

sl=NormalizeDouble(sl,Digits);
tp=NormalizeDouble(tp,Digits);
//--- Open file
int h=FileOpen("Copy.txt",FILE_WRITE,";");
FileSeek(h, 0, SEEK_END);
FileWrite(h,_Symbol,type,sl,tp,lot);
FileClose(h); // close the file

Comment("\n Order Type: ",type,
"Order Lots:",lot,
"StopLoss:",sl,
"TakeProfit:",tp);
}
Купить советник или заказать?
Купить советник или заказать?
  • AM2
  • www.forexsystems.biz
Не секрет, что у каждого трейдера торгующего на рынке Форекс со временем складывается собственная стратегия со своими правилами и запретами. Причем не каждый сможет научиться торговать именно Вашей стратегией в прибыль, даже, если она дает Вам профит в течении продолжительного времени. У каждого свои эмоции, свой характер и свои запросы. Купить...
 
EfremovSergey:

Hi all. I am trying to write each new order in a new line, could you tell me what I am doing wrong? Only the last one opened remains written.


The file keeps getting overwritten because of wrong flags. You need to open the file not only for writing, but also for reading. Then it won't get recreated:

 int h=FileOpen("Copy.txt",FILE_WRITE | FILE_READ,";");
 
Ihor Herasko:

The file is constantly being overwritten because of incorrect flags. You should not only open the file for writing, but also for reading. Then it won't get recreated:

Thank you very much. Thank you very much!

The description of the function itself contains this information, for some reason I missed it and didn't even know which way to go next... I thought I had selected a wrong file type, txt instead of csv, but it turned out to be very simple. )))

 
Can you tell me how to delete a string after reading it, is there any simple way to do it?
 
EfremovSergey:
Can you tell me how to delete a line after reading it, is there any simple way to do it?

In most cases, it is better to read the whole file, make the necessary changes to the data in RAM, and then overwrite the whole file. This is easier than moving the data within the open file.
Документация по MQL5: Файловые операции / FileOpen
Документация по MQL5: Файловые операции / FileOpen
  • www.mql5.com
[in]  Имя открываемого файла, может содержать подпапки. Если файл открывается для записи, то указанные подпапки будут созданы в случае их отсутствия. [in]  значение, используемое в качестве разделителя в txt или csv-файле. Если для csv-файла разделитель не указан, то по умолчанию используется символ табуляции. Если для txt-файла разделитель не...
Reason: