Classe TFiles

Unit

Declaração

type TFiles = class(TConsts)

Descrição

Hierarquia

Visão Geral

Tipos Aninhados

Public TStrError = mi.rtl.Consts.StrError.TStrError;

Métodos

Public class function IsFileOpen(VAR F:Text):BOOLEAN ; overload;
Public class function IsFileOpen(VAR F:File):BOOLEAN ; overload;
Public Class Function AppVersionInfo: TAppVersionInfo;
Public class Function IoResult: Integer;
Public class procedure CtrlSleep(Const Delay: Cardinal);
Public class Function Set_CTRL_SLEEP_ENABLE(Const aEnable: Boolean):Boolean;
Public class function ReadKey: AnsiChar;
Public class procedure SetLastError(aCodeError: integer);
Public class function SetResult(aHandle: THandle ; aSuccess: Boolean): Longint; overload;
Public class function CopyFile(lpExistingFileName, lpNewFileName: AnsiString; aExceptionOnError: boolean): Integer;
Public Class function SetFileMode(aFileMode:word):word;
Public class Function SetStateFileMode(Const AState: Longint; Const Enable: boolean):Boolean;
Public class function GetStateFileMode(Const AState: Longint): Boolean;
Public class function FileOpen(const FileName: AnsiString; const Mode: Longint; const ShareMode : Cardinal; out Handle: THandle): Longint; Overload;
Public Class function FileOpen(const FileName: AnsiString; out Handle: THandle): Longint; Overload;
Public Class function FileClose(Handle: THandle): Longint;
Public class function FileTruncate(Handle:THandle;NewSize:Int64 ): Longint;
Public class function FileCreate(FileName: AnsiString; Mode: Longint; ShareMode : Cardinal; out Handle: THandle): Longint; overload;
Public class function DeleteFile(const FileName : AnsiString): SmallInt ;
Public class function FileSize( FileName: string; out Count : int64):longint; overload;
Public class function FileSize( FileName: string):int64; overload;
Public class function FileSizes(Mask: AnsiString;out aFileSize:Int64): Longint; overload;
Public class function FileSeek(const Handle:THandle; Const FOffset : Int64; Origin: LongInt; out NewPos: Int64): LongInt;
Public class function FileRead(const Handle: THandle; out Buffer; const Count: Int64; out BytesRead: int64): LongInt;
Public class function FileWrite(const Handle: THandle; const Buffer; const Count: Int64; out BytesWrites: int64): LongInt;
Public class Function FileExists(Const FileName : AnsiString) : Boolean;
Public class Function DirectoryExists(Const Directory : AnsiString) : Boolean;
Public class Function CreateDirectory(Const NewDir : AnsiString) : Boolean;
Public class function GetTempFileName(const Dir : string): string ;
Public class function GetTempDir(): string; overload;
Public class function GetTempDir(Const env:String;out path:PathStr):SmallInt; overload;
Public class function GetDriveType(aPath : AnsiString): TDriveType; Overload;
Public Class function DuplicateHandle(var hSource: File;Var lpTarge: File) : Longint; overload;
Public Class function DuplicateHandle(var hSource: Text;Var lpTarge: Text) : Longint; overload;
Public Class function DuplicateHandle(hSourceHandle: THandle;Var lpTargeTHandle: THandle) : Longint; overload;
Public Class function FileFlushBuffers(aHandle: THandle): longint; overload;
Public class function LockFile(_Handle:THandle; _LockStart, _LockLength: Int64): LongInt;
Public class function UnLockFile(_Handle:THandle; _LockStart, _LockLength: Int64): LongInt;
Public class procedure FindFiles(Mask : AnsiString; FileAttrs : Cardinal; var List : TStringList);
Public class procedure FindFilesAll(aPath,Mask : AnsiString; FileAttrs : Cardinal;aRelative:Boolean; var List : TStringList;aSorted:boolean);
Public class function GetCurrentDir: AnsiString;
Public class function SetCurrentDir( const NewDir : AnsiString):Boolean;
Public class function IsDirectory( const Directory : AnsiString):Boolean;
Public class Function FPrimeiroHandleLivre: SmallInt;
Public class function FlockFile(Handle : Thandle; modo : LongInt): LongInt ; overload;
Public class function DiskFree(Partition:byte; out VrDiskFree :Int64):integer;
Public class Function ByteDrive(Const NomeArquivo:AnsiString) : Byte;
Public Class function RewriteFile(aFilePath:AnsiString):Boolean;

Descrição

Tipos Aninhados

Public TStrError = mi.rtl.Consts.StrError.TStrError;
 

Métodos

Public class function IsFileOpen(VAR F:Text):BOOLEAN ; overload;

O método IsFileOpen retorna true se o arquivo F estiver aberto e false caso contrário

Public class function IsFileOpen(VAR F:File):BOOLEAN ; overload;

O método IsFileOpen retorna true se o arquivo F estiver aberto e false caso contrário

Public Class Function AppVersionInfo: TAppVersionInfo;

O método AppVersionInfo contém o número da versão do projeto corrente.

  • Esta contante retira essa informação do arquivo de recursos, caso o projeto não esteja habilitado o número da versão o acesso ao mesmo ao método AppVersionInfo vai gerar excessão.

  • EXEMPLO DE USO

    
    procedure TForm1.Button1Click(Sender: TObject);
    // [0] = Major version, [1] = Minor ver, [2] = Revision, [3] = Build Number
      Var
        sProgName:string;
    begin
    
      With mi.rtl.files.Tfiles do
      begin
    
        sProgName :='PROJECT1';
        edit1.text:=sProgName + ' , Version:     ' + AppVersionInfo.MajorAsStr + '.'+AppVersionInfo.MinorAsStr+'.'+AppVersionInfo.RevisionAsStr+ '.'+AppVersionInfo.BuildNoAsStr;
        edit2.text:=sProgName + ' , VersionStr:  ' + AppVersionInfo.VersionStr;
        edit3.text:=sProgName + ' , VersionStrEx:' + AppVersionInfo.VersionStrEx[C_DEF_VER_FORMAT3];
      end;
    
    end;

Public class Function IoResult: Integer;

A função IoResult captura o estados de system.ioResult e atualiza TaStatus

Public class procedure CtrlSleep(Const Delay: Cardinal);

  • A função CtrlSleep dar opção para que a aplicação execute outras tarefas caso ela se encontre em estado de espera.

    • PARÂMETRO

      • Delay - Tempo em milissegundo que deve aguardar**.

Public class Function Set_CTRL_SLEEP_ENABLE(Const aEnable: Boolean):Boolean;

Public class function ReadKey: AnsiChar;
 
Public class procedure SetLastError(aCodeError: integer);

  • A procedure SetLastError atualiza as variáveis globais LastError e OK

    • PARÂMETROS

      • aCodeError:integer - Código do erro.

    • EXEMPLO

      
      procedure tes_SetLastError();
      Begin
        //Executa a procedure SetLastError
      
        SetLastError(2);
        showMessage(ErrorMessage(LastError));
      
      end;

Public class function SetResult(aHandle: THandle ; aSuccess: Boolean): Longint; overload;

  • A função SetResult captura o último erro se o parâmetro aSucesso=false ou o aHandle for inválido e retorna 0 (zero) se aSucesso=true e o aHandle for válido.

    • A função SetResult atualiza a variável global LastError e a variável global ok:

    • Plataformas testadas

      • win32

      • win64

      • linux

    • PARÂMETROS

      • aHandle - O handle do arquivo retornado pela ultima chamada ao sistema operacional.

      • aSucesso - Recebe true se sucesso ou false se fracasso na última chamada ao sistema operacional.

    • RETORNA

    • NOTA

      • No windows, quando ocorre um erro o handle é igual = high(THandle) por isso é necessário passar o handle do arquivo na chamada a SetResult().

Public class function CopyFile(lpExistingFileName, lpNewFileName: AnsiString; aExceptionOnError: boolean): Integer;

  • A função CopyFile copia o arquivo passado por alpExistingFileName para o arquivo passo por lpNewFileName.

    • PARÂMETROS

      • alpExistingFileName:AnsiString - Nome do arquivo a ser copiado;

      • lpNewFileName:AnsiString - Nome do arquivo destino da cópia;

      • aExceptionOnError:boolean - True se o sistema deve gera exceção ou false se o sistema não deve gera exceção.

    • RETORNO

      • Integer - Código do erro ou 0 (zero) se a cópia for feita com sucesso.

      • Caso o parâmetro aExceptionOnError = true então a exceção deve ser tratada pela rotina que o chamou.

    • EXEMPLO

      
      procedure TFormTests.Button_tes_CopyFileClick(Sender: TObject);
      
        // Este procedimento faz duas cópia do arquivo index.html
      
        Var
          err : TFiles.integer;
      Begin
        with TFiles do
          err := CopyFile('index.html','index.bak1',false);
      
        with TFiles do
        if err = 0
        Then showMessage('Copia 1 feita com sucesso.')
        else showMessage(ErrorMessage(err));
      
        with TFiles do
        try
          CopyFile('index.html','index.bak2',true);
          showMessage('Copia 2 feita com sucesso.') ;
        Except
          on E:Exception do
           ShowMessage(e.Message);
        end;
      end;

Public Class function SetFileMode(aFileMode:word):word;

  • A função SetFileMode modifica o valor de FileMode e retorna o valor do FileMode anterior;

    • PARÂMETROS

      • aFileMode é o modo de abertura do arquivo.

    • RETORNA

    • NOTA

      • A variável pública FileModeAnt é igual ao resultado desta função.

Public class Function SetStateFileMode(Const AState: Longint; Const Enable: boolean):Boolean;

  • Seta FileMode e retorna o estado anterior do Mapa de bits passado por aState

Public class function GetStateFileMode(Const AState: Longint): Boolean;

  • Ler o estado do File Mode

Public class function FileOpen(const FileName: AnsiString; const Mode: Longint; const ShareMode : Cardinal; out Handle: THandle): Longint; Overload;

  • Abre o arquivo passado pelo parâmetro FileName

    • PARÂMETROS

      • FileName - Nome do arquivo a ser aberto;

      • mode - Modo de abertura. Valor possível veja TFileMode;

      • attribute - Atributo de abertura do arquivo;

      • Flags - flag de abertura do arquivo;

      • Handle - Se tiver sucesso retorna nesta variável o número do arquivo aberto;

    • RETORNA

      • LongInt Zero se sucesso ou o código do erro se fracasso.

    • NOTA:

      • Possiveis erros pode ser visto na função ErrorMessage();

    • EXEMPLOS DE USO

      
      procedure TFormTests.Button_Test_OpenFile_exclusive_modeClick(Sender: TObject);
      
        procedure Test_OpenFile_exclusive(aFileName:AnsiString);
        Var
          Err : TFiles.integer;
          h,
          h1 : TFiles.THandle;
        Begin
          with TFiles do
            Err := FileOpen (aFileName, FmReadWrite or FmDenyALL  or fmShareCompat  ,h);
      
          with TFiles do
          if Err = 0
          Then Begin
                 ShowMessage('Teste da função SysFileOpen retornou true');
      
                 Err := FileOpen (aFileName,FmReadWrite or FmDenyALL  or fmShareCompat  ,h1);
                 if Err = 0
                 Then Begin
                        FileClose(h1);
                        ShowMessage('Teste da função SysFileOpen retornou true')
                      end
                 else ShowMessage('Error: '+ErrorMessage(Err));
      
                 FileClose(h);
          end
          else ShowMessage('Error: '+ErrorMessage(Err));
      
        End;
      
      begin
        Test_OpenFile_exclusive('index.html');
      end;

    • REFERÊNCIAS

Public Class function FileOpen(const FileName: AnsiString; out Handle: THandle): Longint; Overload;

  • Abre o arquivo passado pelo parâmetro FileName

    • PARÂMETROS

      • FileName Nome do arquivo a ser aberto;

      • mode - Modo de abertura;

      • Handle - Se result = 0 o Handle contém o número do arquivo aberto, caso contrário, retorna HANDLE_INVALID**;

    • RETORNA

      • 0 (zero) se sucesso ou o código do erro se fracasso;

    • NOTA:

      • Possiveis erros pode ser visto na função ErrorMessage();

    • EXEMPLO DE USO

      
      procedure TFormTests.TestSysOpenFileClick(Sender: TObject);
      Var
        Err : TFiles.Longint;
        h : TFiles.THandle;
      Begin
        with TFiles do
          Err := FileOpen ('index.html',fmOpenRead,h);
      
        with TFiles do
        if Err = 0 Then
        Begin
          FileClose(h);
          ShowMessage('Teste da função FileOpen retornou true')
        end
        else ShowMessage('Error: '+ErrorMessage(Err));
      End;

    • REFERÊNCIAS

Public Class function FileClose(Handle: THandle): Longint;

  • A função FileClose fecha o arquivo passando por Handle.

    • PARÂMETRO

      • Handle - Número do arquivo aberto por FileOpen.

    • RETORNA

      • Zero de tiver sucesso ou o código do erro se não conseguir fechar o arquivo.

    • REFERÊNCIAS

Public class function FileTruncate(Handle:THandle;NewSize:Int64 ): Longint;

  • A função FileTruncate reduz o tamanho do arquivo para o tamanho passado pelo parâmetro NewSize.

    • PARÂMETROS

      • Handle:THandle - Handle do arquivo a ser truncado.

      • NewSize:Int64 - Tamanho do arquivo a se truncado.

    • RETORNO

      • Longint - 0(zero) se sucesso ou o código do erro se fracasso.

    • REFERÊNCIA

    • EXEMPLO

      
      procedure TFormTests.Button_tes_FileTruncateClick(Sender: TObject);
        // Este procedimento Trunca o arquivos 'index.html' para 100 bytes
        Var
          aHandle: TFiles.THandle;
          NewSize: TFiles.word;
          err    : TFiles.integer;
      Begin
        NewSize := 100;
      
        with TFiles do
          err := FileOpen('index.html',fileMode,aHandle);
      
        with TFiles do
        if  err = 0
        then begin
               //Executa a função SysFileTruncate
               err := FileTruncate(aHandle,NewSize);
      
               if err = 0
               then showMessage('O arquivo foi truncado para 100 bytes')
               else ShowMessage('Error: '+ErrorMessage(err));
             end
        else ShowMessage('Error: '+ErrorMessage(err));
      end;

Public class function FileCreate(FileName: AnsiString; Mode: Longint; ShareMode : Cardinal; out Handle: THandle): Longint; overload;

  • A função FileCreate cria um novo arquivo e retorna um identificador para ele ou código do erro houver fracasso.

    • PARÂMETROS

      • FileName: AnsiString - Nome do arquivo a ser criado;

      • Mode: Longint - Modo de criação do arquivo. Veja FileMode para mais informações;

    • RETORNO

      • THandle - Handle do arquivo criado;

      • LongInt - 0 (zero se sucesso ou o código do erro se fracasso.

    • EXEMPLO

      
      procedure TFormTests.Button_test_FileCreateClick(Sender: TObject);
      
        function tes_FileCreate(FileName:AnsiString;out aHandle:THandle): LongInt;
        Begin
          with TFiles do
            result := FileCreate(FileName,fmOpenReadWrite or fmShareExclusive,aHandle);
        end;
      
      var
        aHandle :  TFiles.THandle;
      begin
      
        with TFiles do
        if tes_FileCreate('text.txt',aHandle) = 0
        then begin
               showMessage('Arquivo text.txt criado na pasta corrente.');
               FileClose(aHandle);
             end;
      end;

Public class function DeleteFile(const FileName : AnsiString): SmallInt ;
 
Public class function FileSize( FileName: string; out Count : int64):longint; overload;

  • A função FileSize retorna o tamanho do arquivo em bytes.

    • PARÂMETROS

      • FileName: AnsiString - Nome do arquivo;

      • Count: Int64 - Número de bytes do arquivo passo do FileName.

    • RETORNO

      • longint - 0 (zero) se sucesso ou o código do erro se houver fracasso;

      • Count - Número de bytes do arquivo.

    • EXEMPLO

      
       procedure TMi_Rtl_Tests.Action_Test_FileSizeExecute(Sender: TObject);
           // Este procedimento obtem o tamanho do arquivo em bytes do arquivo index.html;
         var
           FileName:AnsiString;
           Count:Int64;
           err:Longint;
       Begin
         with TFiles do
         begin
           FileName := 'index.html';
           err := FileSize(FileName,Count);
           if err <> 0
           Then showMessage(ErrorMessage(err))
           else showMessage('Tamanho do arquivo é: '+intToStr(Count));
         end;
      end;

Public class function FileSize( FileName: string):int64; overload;
 
Public class function FileSizes(Mask: AnsiString;out aFileSize:Int64): Longint; overload;

O função FileSizes retorna em aFileSize a soma de todos os arquivos que satisfaça a mascara em path;

Public class function FileSeek(const Handle:THandle; Const FOffset : Int64; Origin: LongInt; out NewPos: Int64): LongInt;

  • A função FileSeek posiciona o ponteiro do arquivo na posição FOffSet começando da origem.

    • PARÂMETROS

    • RETORNO

      • LongInt - 0 (zero se sucesso ou código do erro se fracasso.

        • Em NewPos retorna o número da posição atual do arquivo.

      • EXEMPLO

        
        procedure TMi_Rtl_Tests.Action_Test_FileSeekExecute(Sender: TObject);
          // Este procedimento posiciona o cursor no final do arquivo.
          Var
            err : TFiles.integer;
            h   : TFiles.THandle;
            NRec,Count : TFiles.Int64;
        Begin
          with TFiles do
          begin
            err := FileOpen('index.html',h);
            if (err = 0) and (fileSize('index.html',Count) = 0)
            Then Begin
                   //Posiciona no final do arquivo
                   err := FileSeek(h,Count,fsFromBeginning,NRec);
                   if err <> 0
                   Then ShowMessage(ErrorMessage(err));
                   FileClose(h);
                 end
            else ShowMessage(ErrorMessage(err));
          end;
        end;

    • REFERÊNCIA:

Public class function FileRead(const Handle: THandle; out Buffer; const Count: Int64; out BytesRead: int64): LongInt;

  • O método FileRead ler Count bytes do arquivo passado pelo Handle e retorna o número de bytes lidos em BytesRead

    • PARÂMETROS

      • Handle: THandle - Handle do arquivo

      • Out Buffer - Buffer para onde os dados devem ser salvos;

      • Count: Int64 - Número de bytes a ser lido para o buffer;

      • Out BytesRead: Int64 - Número de Bytes lidos efetivamente.

    • RETORNO

      • Longint - 0 (zero se sucesso ou o código do erro se fracasso;

      • Em Buffer os dados lidos do arquivo;

      • Em BytesRead Retorna o número de bytes lidos efetivamente.

      • EXEMPLO

        
        procedure TMi_Rtl_Tests.Action_Test_FileReadExecute(Sender: TObject);
          // Este procedimento ler os últimos 10 bytes do arquivo index.html
          Const Size = 10;
          Var
            err  : TFiles.integer;
            h    : TFiles.THandle;
            NRec,
            Count : TFiles.Int64;
            s     : String[255];
            BytesLidos: Int64;
        Begin
          with TFiles do
          begin
        
            err := FileOpen('index.html',h);
            if (err = 0)
            Then Begin
                   err := fileSize('index.html',Count);
                   if ( err = 0)
                   Then begin
                         //Posiciona no final do arquivo
                         err := FileSeek(h,Count-Size-length(LF),fsFromBeginning,NRec);
                         if err <> 0
                         Then ShowMessage(ErrorMessage(err))
                         Else Begin
                                err := FileRead(h,s[1],Size+length(LF),BytesLidos);
                                if (err = 0) and (BytesLidos = Size+length(LF))
                                Then Begin
                                       s[0] := chr(Size);
                                       ShowMessage('Bytes Lidos: '+s);
                                     end
                                else ShowMessage('Ponteiro do arquivo é: '+IntToStr(NRec));
                              end;
        
                   end
                   else ShowMessage(ErrorMessage(err));
                   FileClose(h);
                 end
            else ShowMessage(ErrorMessage(err));
          end;
        end;

    • REFERÊNCIA

Public class function FileWrite(const Handle: THandle; const Buffer; const Count: Int64; out BytesWrites: int64): LongInt;

  • O método FileWrite grava Count bytes do arquivo passado pelo Handle e retorna o número de bytes escritos em BytesWrite

    • PARÂMETROS

      • Handle: THandle - Handle do arquivo

      • Out Buffer - Buffer de onde os dados devem ser escritos para o arquivo;

      • Count: Int64 - Número de bytes a ser escritos do Buffer para o arquivo;

      • Out BytesRead: Int64 - Número de Bytes efetivamente escritos.

    • RETORNO

      • Longint - 0 (zero se sucesso ou o código do erro se fracasso;

      • Em Buffer os dados as ser escrito no arquivo;

      • Em BytesRead Retorna o número de bytes escritos efetivamente.

      • EXEMPLO

        
        
        procedure TMi_Rtl_Tests.Action_Test_FileWriteExecute(Sender: TObject);
        
          // Este procedimento adiciona a sequência '-0123456789-0123456789'+LF no fim do arquivo index.html
        
          Var
            Size : byte = 255;
            err  : TFiles.integer;
            h    : TFiles.THandle;
        
            NRec, Count : TFiles.Int64;
        
            s     : String[255];
        
            BytesLidos,BytesWrites: Int64;
        Begin
          with TFiles do
          begin
            s :=  '-0123456789-0123456789'+LF;
            Size := length(s);
        
            if not FileExists('index.html')
            Then Err := FileCreate('index.html',fmOpenReadWrite, fmShareCompat or fmShareDenyNone ,h)
            else Err := FileOpen('index.html',h);
        
            if (err = 0)
            Then Begin
                   err := fileSize('index.html',Count);
                   if ( err = 0)
                   Then begin
                          //Posiciona no final do arquivo - length(LF)
                          if Count >= size
                          then err := FileSeek(h,Count-length(LF),fsFromBeginning,NRec)
                          else err := FileSeek(h,0,fsFromBeginning,NRec);
        
                          if err = 0
                          Then Begin
                                 //Acressenta string '-0123456789-0123456789'+LF no arquivo 'index.html'
                                 err:= FileWrite(h,s[1],length(s),BytesWrites);
                                 if (err = 0) and (BytesWrites = (length(s)))
                                 then Begin
                                        ShowMessage('A sequência '+S+' foi adicionada no fim do arquivo.')
                                      end
                                 else begin
                                        if (err <> 0)
                                        Then ShowMessage(ErrorMessage(err))
                                        else ShowMessage('Número de bytes escritos diferente de: '+IntToStr(length(s)));
                                      end;
                               end
                          else Begin
                                 ShowMessage(ErrorMessage(err))   ;
                               end;
                   end
                   else ShowMessage(ErrorMessage(err));
                   FileClose(h);
                 end
            else ShowMessage(ErrorMessage(err));
          end;
        end;

    • REFERÊNCIA

Public class Function FileExists(Const FileName : AnsiString) : Boolean;

  • A classe método FileExists checa se o arquivo passado no parâmetro existe.

Public class Function DirectoryExists(Const Directory : AnsiString) : Boolean;

  • A classe método DirectoryExists checa se o diretório passado no parâmetro existe

Public class Function CreateDirectory(Const NewDir : AnsiString) : Boolean;

  • A classe método CreateDirectory cria diretório passado pelo parâmetro NewDir

Public class function GetTempFileName(const Dir : string): string ;

A classe método GetTempFileName retorna o nome de um arquivo temporário no diretório Dir.

  • NOTA

    • Se Dir estiver vazio, o valor retornado por GetTempDir será usado.

    • O Prefix será 'TMP'.

    • Em caso de erro, uma string vazia é retornada.

Public class function GetTempDir(): string; overload;

A classe function GetTempDir retorna o diretório temporário do sistema.

  • NOTA

    • O nome retornado terminará com um caractere delimitador de diretório.

    • Não há garantia de que esse diretório exista ou seja gravável pelo usuário.

Public class function GetTempDir(Const env:String;out path:PathStr):SmallInt; overload;

A classe function GetTempDir retorna o diretório temporário do sistema.

  • PARÂMETROS

    • Const env : Variável de ambiente que tenha que contenha a pasta de arquivos temporários.

    • **out path:PathStr : Retorna a pasta dos arquivos temporários.

  • RETORNA

    • SmallInt : Código do erro se houver ou zero (0) se conseguiu gerar o nome da pasta.

Public class function GetDriveType(aPath : AnsiString): TDriveType; Overload;

  • A função GetDriveType é usada para saber o tipo de dispositivo associado a pasta.

    • PARÂMETRO

      • aPath - A pasta dona do arquivo.

    • RETORNA

Public Class function DuplicateHandle(var hSource: File;Var lpTarge: File) : Longint; overload;

  • A classe método DuplicateHandle duplica o handle do arquivo no windows e linux.

Public Class function DuplicateHandle(var hSource: Text;Var lpTarge: Text) : Longint; overload;

  • A classe método DuplicateHandle duplica o handle do arquivo no windows e linux.

Public Class function DuplicateHandle(hSourceHandle: THandle;Var lpTargeTHandle: THandle) : Longint; overload;

  • A classe método DuplicateHandle duplica o handle do arquivo no windows e no linux essa função não funciona.

Public Class function FileFlushBuffers(aHandle: THandle): longint; overload;

A classe function FileFlushBuffers descarrega o buffer do arquivo passado por aHandle

Public class function LockFile(_Handle:THandle; _LockStart, _LockLength: Int64): LongInt;

Public class function UnLockFile(_Handle:THandle; _LockStart, _LockLength: Int64): LongInt;

  • A classe método UnLockFile destrava a região travada por LockFile.

    • NOTA

      • Funciona no windows mais não funciona do linux.

Public class procedure FindFiles(Mask : AnsiString; FileAttrs : Cardinal; var List : TStringList);

  • A classe método FindFiles retorna uma lista de nomes de arquivos e diretórios que satisfazem os parâmetros: Mask e FileAttrs

    • EXEMPLO DE USO

      
      procedure TMi_Rtl_Tests.FormCreate(Sender: TObject);
      begin
        ListFiles := TMiStringList.Create;
        Action_test_FindFirstExecute(Self);
      end;
      
      procedure TMi_Rtl_Tests.Action_test_FindFirstExecute(Sender: TObject);
        //Este procedimento ler os atributos da pasta: '.'
      
        function GetInfoFile(FileName:string;attribute : Cardinal; out info : TSearchRec): Integer;
      
        begin
           Result := FindFirst(ExpandFileName(FileName),attribute,Info);
           if Result = 0
           then Begin
                  ShowMessage('O arquivo '+fileName+' contém o atributo: '+intToStr(attribute));
                end
           else begin
                  ShowMessage('O arquivo '+fileName+' não contém o atributo: '+intToStr(attribute));
                end;
        end;
      
        var
         Info: TSearchRec;
         err,i : integer;
      
         const FileAttrs : Cardinal = faHidden or
                                      faReadOnly or
                                      faSysFile or
                                      faArchive or
                                      faAnyFile or
                                      faSymLink or
                                      faDirectory ;
      
      
      begin
        ListFiles.Clear;
        ListBox1.Clear;
      
        FileAttrs := 0;
      
        if CheckBox_faHidden.Checked
        then FileAttrs := faHidden;
      
        if CheckBox_faReadOnly.checked
        then FileAttrs := FileAttrs or faReadOnly;
      
        if CheckBox_faSysFile.checked
        then FileAttrs := FileAttrs or faSysFile;
      
        if CheckBox_faArchive.checked
        then FileAttrs := FileAttrs or faArchive;
      
        if CheckBox_faAnyFile.checked
        then FileAttrs := FileAttrs or faAnyFile;
      
        if CheckBox_faSymLink.checked
        then FileAttrs := FileAttrs or faSymLink;
      
        if CheckBox_faDirectory.checked
        then FileAttrs := FileAttrs or faDirectory;
      
        with TMI_ui_types do
          FindFiles(Edit1.Text,FileAttrs ,ListFiles );
      
        LabelCount.Caption := Format('ListFiles.Count %d',[ListFiles.Count]);
        LabelCount.Show;
        if ListFiles.Count > 0
        then begin
                for i := 0 to ListFiles.Count-1 do
                begin
                  ListBox1.Items.Add(ListFiles[i]);
                end;
             end;
      end;
      
      
      procedure TMi_Rtl_Tests.Edit1Change(Sender: TObject);
      begin
        Action_test_FindFirstExecute(Self);
      end;
      
      procedure TMi_Rtl_Tests.CheckBox_faAnyFileChange(Sender: TObject);
      begin
        Action_test_FindFirstExecute(Self);
      end;
      
      procedure TMi_Rtl_Tests.CheckBox_faArchiveChange(Sender: TObject);
      begin
        Action_test_FindFirstExecute(Self);
      end;
      
      procedure TMi_Rtl_Tests.CheckBox_faDirectoryChange(Sender: TObject);
      begin
        Action_test_FindFirstExecute(Self);
      end;
      
      procedure TMi_Rtl_Tests.CheckBox_faHiddenChange(Sender: TObject);
      begin
        Action_test_FindFirstExecute(Self);
      end;
      
      procedure TMi_Rtl_Tests.CheckBox_faReadOnlyChange(Sender: TObject);
      begin
        Action_test_FindFirstExecute(Self);
      end;
      
      procedure TMi_Rtl_Tests.CheckBox_faSymLinkChange(Sender: TObject);
      begin
        Action_test_FindFirstExecute(Self);
      end;
      
      procedure TMi_Rtl_Tests.CheckBox_faSysFileChange(Sender: TObject);
      begin
        Action_test_FindFirstExecute(Self);
      end;

Public class procedure FindFilesAll(aPath,Mask : AnsiString; FileAttrs : Cardinal;aRelative:Boolean; var List : TStringList;aSorted:boolean);

A class método FindFilesAll retorna em List todos os arquivos, inclusives os arquivos dos subdiretórios que satisfazem os parâmetros: Mask e FileAttrs.

  • Notas

    • Suponha a pasta views contendo as pastas pages e partial contendo os seguintes arquivos:

      
      views/
      ├── pages
      │   ├── about.ejs
      │   ├── about.html
      │   ├── index.ejs
      │   └── index.html
      └── partials
          ├── footer.ejs
          ├── head.ejs
          └── header.ejs

    • Efeito esperado da função FindFilesAll é equivalente ao comando linux abaixo:

      
      find ./ -iname *.ejs
      
      > ./pages/index.ejs
      > ./pages/about.ejs
      > ./partials/head.ejs
      > ./partials/header.ejs
      > ./partials/footer.ejs

  • EXEMPLO

    
    procedure TForm1.Action_test_FindFirstExecute(Sender: TObject);
      //Este procedimento ler os atributos da pasta: '.'
    
      var
       i : integer;
       const FileAttrs : Cardinal = faHidden or
                                    faReadOnly or
                                    faSysFile or
                                    faArchive or
                                    faAnyFile or
                                    faSymLink or
                                    faDirectory ;
    
    
    begin
      ListFiles.Clear;
      ListBox1.Clear;
      ListBox1.Hide;
      FileAttrs := 0;
    
      if CheckBox_faHidden.Checked
      then FileAttrs := faHidden;
    
      if CheckBox_faReadOnly.checked
      then FileAttrs := FileAttrs or faReadOnly;
    
      if CheckBox_faSysFile.checked
      then FileAttrs := FileAttrs or faSysFile;
    
      if CheckBox_faArchive.checked
      then FileAttrs := FileAttrs or faArchive;
    
      if CheckBox_faAnyFile.checked
      then FileAttrs := FileAttrs or faAnyFile;
    
      if CheckBox_faSymLink.checked
      then FileAttrs := FileAttrs or faSymLink;
    
      if CheckBox_faDirectory.checked
      then FileAttrs := FileAttrs or faDirectory;
    
      with TObjectss do
       FindFilesAll(GetCurrentDir,*.html,FileAttrs ,ListFiles );
       // Quando o path não informado, FindFileAll seleciona todos os arquivos apartir da pasta atual.
       FindFilesAll('',*.html,FileAttrs ,ListFiles );
    
      LabelCount.Caption := Format('ListFiles.Count %d',[ListFiles.Count]);
      LabelCount.Show;
    
    
      if ListFiles.Count > 0
      then begin
              for i := 0 to ListFiles.Count-1 do
              begin
                ListBox1.Items.Add(ListFiles[i]);
              end;
           end;
      ListBox1.Show;
    end;

Public class function GetCurrentDir: AnsiString;

A classe método GetCurrentDir retorna o corrente pasta.

Public class function SetCurrentDir( const NewDir : AnsiString):Boolean;

A classe método SetCurrentDir define a pasta passado por NewDir como pasta corrente.

PARÂMETRO

  • NewDir - Nome da pasta a ser definida.

RETORNA

  • TRUE - Se sucesso

  • FALSE - Se fracasso;

Public class function IsDirectory( const Directory : AnsiString):Boolean;

A classe método IsDirectory checa se a pasta passado por Directory é uma pasta válida.

PARÂMETRO

  • Directory - Nome da pasta

RETORNA

  • TRUE - Se a pasta existe

  • FALSE - Se a pasta não existe;

Public class Function FPrimeiroHandleLivre: SmallInt;

Retorna o numero de arquivos abertos no sistema operacional

  • NOTA

    • TaStaus : Retorna o número do error se ouver

Public class function FlockFile(Handle : Thandle; modo : LongInt): LongInt ; overload;

A class function FlockFile define ou remove um bloqueio no arquivo passado por Handle.

  • PARÂMETROS

    • MODE

      • O modo pode ser uma das seguintes constantes:

        • LOCK_SH : define um bloqueio compartilhado.

        • LOCK_EX : define um bloqueio exclusivo.

        • LOCK_UN : desbloqueia o arquivo.

        • LOCK_NB : Isso pode ser OR junto com o outro. Se isso for feito, o aplicativo não bloqueia ao bloquear.

  • RETORNO

    • LONGINT : A função retorna zero se for bem-sucedida, um valor de retorno diferente de zero indica um erro.

  • REFERÊNCIA

Public class function DiskFree(Partition:byte; out VrDiskFree :Int64):integer;

A class function DiskFree retorna o espaço livre (EM BYTES) da partição passada por Partition

  • PARÂMETRO:

    • 0 para a partição atual.

    • 1 para a primeira unidade de disquete.

    • 2 Para a segunda unidade de disquete.

    • 3 Para a primeira partição do disco rígido.

    • 4-26 Para todas as outras unidades e partições.

  • REFERÊNCIA:

  • OBSERVAÇÃO:

    • No Linux, e no Unix em geral, o conceito de disco é diferente do dos um, uma vez que o sistema de arquivos é visto como uma grande árvore de diretórios. Por esta razão, os DiskFree e DiskSize funções devem ser mimetizado utilizando nomes de arquivos que residem nas partições. Para obter mais informações, consulte AddDisk.

  • EXEMPLO:

    
    procedure testDiskFree;
       var
         VrDiskFree : int64;
    begin
      WriteLn('TestDiskFree;');
    
      VrDiskFree := Diskfree(0);
      Writeln ('Free space of current disk: ',VrDiskFree, ' Bytes');
    
      VrDiskFree := (VrDiskFree div 1024);
      Writeln ('Free space of current disk: ',VrDiskFree,' KB)');
    
      VrDiskFree := (VrDiskFree div 1024);
      Writeln ('Free space of current disk: ',VrDiskFree,' MB)');
    
      VrDiskFree := (VrDiskFree div 1024);
      Writeln ('Free space of current disk: ',VrDiskFree,' GB)');
    
      VrDiskFree := (VrDiskFree div 1024);
      Writeln ('Free space of current disk: ',VrDiskFree,' TB)');
    end;

Public class Function ByteDrive(Const NomeArquivo:AnsiString) : Byte;
 
Public Class function RewriteFile(aFilePath:AnsiString):Boolean;

A classe método RewriteFile cria as pastas e arquivo em disco se o mesmo não existir.


Gerado por PasDoc 0.16.0.