FileWriteArray
FileWriteArray
函数可以编辑除字符串类型外任何类型的数组到BIN文件中(可以是不包含字符串或动态数组的结构数组)。
uint FileWriteArray(
int file_handle, // 文件句柄
const void& array[], // 数组
int start=0, // 数字中启动索引
int count=WHOLE_ARRAY // 单元号
);参量
- file_handle
[in] 通过 FileOpen()返回文件说明符。
- array[]
[out] 记录数组。
- start=0
[in] 数组的原始索引(第一个记录元素的号码)。
- count=WHOLE_ARRAY
[in] 记录项目数量 (WHOLE_ARRAY 表示记录所有以 start 开头的项目指导数组末尾)。
返回值
记录项目数量。
注释
字符串数组可以记录在TXT文件中,字符串可以自动以 “\r\n"字节结尾,依据文件类型ANSI 或者 UNICODE,字符串可以转换成ANSI编码。
示例 :
//+------------------------------------------------------------------+
//| Demo_FileWriteArray.mq5 |
//| Copyright 2013, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2013, MetaQuotes Software Corp."
#property link "https://www.mql5.com"
#property version "1.00"
//--- 输入参数
input string InpFileName="data.bin";
input string InpDirectoryName="SomeFolder";
//+------------------------------------------------------------------+
//| 存储价格数据的结构 |
//+------------------------------------------------------------------+
struct prices
{
datetime date; // 日期
double bid; // 买入价
double ask; // 卖出价
};
//--- 全局变量
int count=0;
int size=20;
string path=InpDirectoryName+"//"+InpFileName;
prices arr[];
//+------------------------------------------------------------------+
//| 专家初始化函数 |
//+------------------------------------------------------------------+
int OnInit()
{
//--- 为数组分配内存
ArrayResize(arr,size);
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| 专家去初始化函数 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- 如果计数,编写其余的计数字符串<n
WriteData(count);
}
//+------------------------------------------------------------------+
//| 专家订单号函数 |
//+------------------------------------------------------------------+
void OnTick()
{
//--- 保存数组数据
arr[count].date=TimeCurrent();
arr[count].bid=SymbolInfoDouble(Symbol(),SYMBOL_BID);
arr[count].ask=SymbolInfoDouble(Symbol(),SYMBOL_ASK);
//--- 显示当前数据
Print("Date = ",arr[count].date," Bid = ",arr[count].bid," Ask = ",arr[count].ask);
//--- 增加计数器
count++;
//--- 如果填写数组,向文件写入数据和零
if(count==size)
{
WriteData(size);
count=0;
}
}
//+------------------------------------------------------------------+
//| 向文件写下数组的n元素 |
//+------------------------------------------------------------------+
void WriteData(const int n)
{
//--- 打开文件
ResetLastError();
int handle=FileOpen(path,FILE_READ|FILE_WRITE|FILE_BIN);
if(handle!=INVALID_HANDLE)
{
//--- 向文件结尾写下数组数据
FileSeek(handle,0,SEEK_END);
FileWriteArray(handle,arr,0,n);
//--- 关闭文件
FileClose(handle);
}
else
Print("Failed to open the file, error ",GetLastError());
}