跳至内容

FileFindFirst

FileFindFirst

此函数根据指定的过滤器开始搜索目录中的文件或子目录。

long  FileFindFirst(
   const string   file_filter,          // String - search filter
   string&        returned_filename,    // Name of the file or subdirectory found
   int            common_flag=0         // Defines the search
   );

参数

file_filter

[in] 搜索过滤器。可以在过滤器中指定相对于\Files目录的子目录(或嵌套子目录序列),在这些子目录中需要搜索文件。

returned_filename

[out] 返回的参数,如果成功,则包含找到的第一个文件或子目录的名称。仅返回文件名(包括扩展名),无论是否在搜索过滤器中指定了目录和子目录,都不会包括它们。

common_flag

[in] 标志,用于确定文件的存储位置。如果common_flag = FILE_COMMON,则文件位于所有客户端终端的共享文件夹\Terminal\Common\Files中。否则,文件位于本地文件夹中。

返回值

返回被搜索对象的句柄,该句柄可用于通过FileFindNext()函数进一步排序文件和子目录,或者当没有与过滤器匹配的文件和子目录时返回INVALID_HANDLE(特别是在目录为空的情况下)。搜索后,必须使用FileFindClose()函数关闭该句柄。

注意

出于安全原因,在MQL4语言中处理文件受到严格控制。使用MQL4进行文件操作的文件不能位于文件沙箱之外。

示例:

//--- display the window of input parameters when launching the script
#property script_show_inputs
//--- filter
input string InpFilter="Dir1\\*";
//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
  {
   string file_name;
   string int_dir="";
   int    i=1,pos=0,last_pos=-1;
//--- search for the last backslash
   while(!IsStopped())
     {
      pos=StringFind(InpFilter,"\\",pos+1);
      if(pos>=0)
         last_pos=pos;
      else
         break;
     }
//--- the filter contains the folder name
   if(last_pos>=0)
      int_dir=StringSubstr(InpFilter,0,last_pos+1);
//--- get the search handle in the root of the local folder
   long search_handle=FileFindFirst(InpFilter,file_name);
//--- check if the FileFindFirst() is executed successfully
   if(search_handle!=INVALID_HANDLE)
     {
      //--- in a loop, check if the passed strings are the names of files or directories
      do
        {
         ResetLastError();
         //--- if it's a file, the function returns true, and if it's a directory, it returns error ERR_FILE_IS_DIRECTORY
         FileIsExist(int_dir+file_name);
         PrintFormat("%d : %s name = %s",i,GetLastError()==ERR_FILE_IS_DIRECTORY ? "Directory" : "File",file_name);
         i++;
        }
      while(FileFindNext(search_handle,file_name));
      //--- close the search handle
      FileFindClose(search_handle);
     }
   else
      Print("Files not found!");
  }

另请参阅

FileFindNext(), FileFindClose()

最后更新于