SysGetFileInfos, obtenha informações sobre arquivos

Lista

Esta página faz parte do Manual de Programação IEC 61131-3. Acesse o índice.

Este bloco de função de executar na tarefa Voltar, retorna informações sobre arquivos ou diretórios individuais ou sobre arquivos ou diretórios contidos em um diretório. passando PathNane o arquivo completo ou nome do diretório do caminho e ativando Init, se o arquivo ou diretório estiver presente, as informações serão retornadas.

Listar todos os arquivos em uma pasta

Definindo em PathName o nome de uma pasta seguido do filtro “/*.*”, ativando  Init a lista de arquivos é inicializada e o primeiro arquivo encontrado é retornado. Em todo comando Next uma busca por um novo arquivo é realizada, se a saída do arquivo for encontrada Found é ativado para um loop e seu nome é retornado para Name. Terminou a lista de todos os arquivos presentes no comando Next a saída não está mais ativada Found e Name está listado.

Também é possível realizar um filtro nos arquivos a serem retornados. Por exemplo, usando “/*.htm” somente os arquivos com a extensão “htm” são retornados. A saída IsDir ele é ativado se o nome do arquivo retornado for o de um subdiretório

Substitui SysDirListing

Substitui o bloco de funções SysDirListing, alterando o tipo de parâmetros de entrada e saída de string para ponteiro de string. A declaração anterior:

VAR
    DList : SysDirListing; (* Get file infos *)
END_VAR

DList.PathName:='C:/';
DList();
IF (DList.Found) THEN i:=SysVfprintf(Fp, ADR('%s'), VR_TYPE#STRING_TYPE, ADR(DList.Name)); END_IF;

Torna-se:

VAR
    DList : SysGetFileInfos; (* Get file infos *)
END_VAR

DList.PathName:=ADR('C:/');
DList();
IF (DList.Found) THEN i:=SysVfprintf(Fp, ADR('%s'), VR_TYPE#STRING_TYPE, DList.Name); END_IF;
Círculo de Informação

Bloqueio de função

CoDeSys: Indisponível

Laboratório de lógica: eLLabXUnified12Lib

descrição

Init (BOOL) Na ativação, o índice dos arquivos no diretório indicado é inicializado e o nome do primeiro arquivo encontrado é retornado.
Next (BOOL) Após a ativação, é retornado o nome do arquivo apontado pelo índice no diretório indicado. O índice é incrementado apontando para o próximo arquivo.
PathName (@STRING) Nome do arquivo completo com caminho.
Para detectar os dados de um arquivo específico, defina seu caminho e nome, por exemplo C:\MyDir\MyFile.log.
Para detectar dados de um diretório, defina seu caminho, por exemplo C:\MyDir\MyFile.log.
Para listar arquivos em um diretório, defina o caminho com o filtro de exemplo C:\MyDir\*.log.
Found (BOOL) Ativa para um loop se estiver sob comando Init o Next um arquivo foi encontrado.
Fault (BOOL) Ativa para um loop em caso de erro de execução.
IsDir (BOOL) Ativo se o nome do arquivo retornado pertencer a um subdiretório.
Size (UDINT) Tamanho do arquivo.
FTime (UDINT) Data da última modificação do arquivo no horário Epoch (UTC).
Name (@STRING) Nome do arquivo incluindo qualquer extensão

Imagem de SysGetFileInfos FB

Exemplos

Como usar os exemplos.

ST_SysGetFileInfos: Por conexão telnet à porta indicada, é retornado o final dos arquivos e diretórios encontrados no caminho definido.

ST_DeleteOldestFiles: Ativando a variável de depuração Delete, os arquivos no diretório definido são verificados e os mais antigos são excluídos para manter o número total de arquivos igual ao valor de Threshold.

Outros exemplos são encontrados na função Sysremove.

LogicLab (Ptp116, ST_SysGetFileInfos)
PROGRAM ST_SysGetFileInfos
VAR
    i : UDINT; (* Auxiliary variable *)
    CaseNr : USINT; (* Program case *)
    FFound : USINT; (* Files found *)
    Fp : eFILEP; (* File pointer array *)
    DFound : USINT; (* Directories found *)
    LDTime : LDATETIMESTRUCT; (* Date/Time struct *)
    TCPServer : SysTCPServer; (* TCP server *)
    DList : SysGetFileInfos; (* Get file infos *)
END_VAR

// *****************************************************************************
// PROGRAM "ST_SysGetFileInfos"
// *****************************************************************************
// When a telnet client connect to port 1200 it's executed the listing of
// a directory.
// -----------------------------------------------------------------------------

    // -------------------------------------------------------------------------
    // INITIALIZATION
    // -------------------------------------------------------------------------
    // Program initializations.

    IF (SysFirstLoop) THEN

        // TCPServer initialization.

        TCPServer.FilesArr:=ADR(Fp); //Files array
        TCPServer.LocalAdd:=ADR('0.0.0.0'); //Local address
        TCPServer.LocalPort:=1200; //Local port 
        TCPServer.MaxConn:=1; //Accepted connections
        TCPServer.FlushTm:=50; //Flush time (mS)
        TCPServer.LifeTm:=30; //Life time (S)
        TCPServer.RxSize:=128; //Rx buffer size
        TCPServer.TxSize:=128; //Tx buffer size

        // Directory listing initialization.

        DList.PathName:=ADR('/tmp/*.*'); //Directory to list    
        DList.PathName:=ADR('C:/*.*'); //Directory to list    
    END_IF;

    // -------------------------------------------------------------------------
    // TCP SERVER MANAGEMENT
    // -------------------------------------------------------------------------
    // Manage the TCP server and directory listing.

    DList(); //Directory listing
    TCPServer(); //TCPServer management
    TCPServer.Enable:=TRUE; //TCPServer enable

    // Check if a client has been connected.

    IF NOT(SysFIsOpen(Fp)) THEN CaseNr:=0; RETURN; END_IF;

    // -------------------------------------------------------------------------
    // PROGRAM CASES
    // -------------------------------------------------------------------------
    // Program case management.

    CASE (CaseNr) OF

        // ---------------------------------------------------------------------
        // Init listing.

        0:
        DFound:=0; //Directories found
        FFound:=0; //Files found
        DList.Init:=TRUE; //Init listing
        i:=SysVfprintf(Fp, ADR('%s$r$n$r$n'), VR_TYPE#STRING_TYPE, ADR('"SysDirListing" example program'));
        CaseNr:=10; //Program case        

        // ---------------------------------------------------------------------
        // Init listing.

        1:
        DList.Next:=TRUE; //Next command
        CaseNr:=10; //Program case        

        // ---------------------------------------------------------------------
        // Reset commands.

        10:
        DList.Init:=FALSE; //Init listing
        DList.Next:=FALSE; //Next command

        // If file found returns file data.

        IF (DList.Found) THEN

            // Returns Date/Time.

            i:=SPLIT_DT(TO_DATE_AND_TIME(DList.FTime), ADR(LDTime.Year), ADR(LDTime.Month), ADR(LDTime.Day), ADR(LDTime.Hours), ADR(LDTime.Minutes), ADR(LDTime.Seconds));
            i:=SysVfprintf(Fp, ADR('%02d/'), VR_TYPE#UINT_TYPE, ADR(LDTime.Day));
            i:=SysVfprintf(Fp, ADR('%02d/'), VR_TYPE#UINT_TYPE, ADR(LDTime.Month));
            i:=SysVfprintf(Fp, ADR('%04d'), VR_TYPE#UINT_TYPE, ADR(LDTime.Year));

            i:=SysVfprintf(Fp, ADR(' %02d:'), VR_TYPE#UINT_TYPE, ADR(LDTime.Hours));
            i:=SysVfprintf(Fp, ADR('%02d'), VR_TYPE#UINT_TYPE, ADR(LDTime.Minutes));

            // Returns directory label or file length.

            IF (DList.IsDir) THEN
                DFound:=DFound+1; //Directories found
                i:=SysVfprintf(Fp, ADR(' %10s'), VR_TYPE#STRING_TYPE, ADR('[DIR]'));
            ELSE
                FFound:=FFound+1; //Files found
                i:=SysVfprintf(Fp, ADR(' %10d'), VR_TYPE#UDINT_TYPE, ADR(DList.Size));
            END_IF;

            // Returns file name.

            i:=SysVfprintf(Fp, ADR(' %s$r$n'), VR_TYPE#STRING_TYPE, DList.Name);
            CaseNr:=20; //Program case
            RETURN;        
        END_IF;

        // All files in the directory have been listed.        

        i:=SysVfprintf(Fp, ADR('%16d Files$r$n'), VR_TYPE#USINT_TYPE, ADR(FFound));
        i:=SysVfprintf(Fp, ADR('%16d Directory$r$n'), VR_TYPE#USINT_TYPE, ADR(DFound));
        CaseNr:=30; //Program case

        // ---------------------------------------------------------------------
        // Wait until the output buffer is empty.

        20, 30:
        IF (TO_UDINT(SysFGetOSpace(Fp)) <> SysFGetOBfSize(Fp)) THEN RETURN; END_IF;
        IF (CaseNr = 30) THEN i:=Sysfclose(Fp); END_IF; //Close socket
        CaseNr:=1; //Program case        
    END_CASE;

// [End of file]
LogicLab (Ptp116, ST_DeleteOldestFiles)
PROGRAM ST_DeleteOldestFiles
VAR
    CaseNr : USINT; (* Program case *)
    FFound : USINT; (* Files found *)
    i : UDINT; (* Auxiliary variable *)
    DList : SysGetFileInfos; (* Directory listing *)
    Delete : BOOL; (* Delete files command *)
    FDate : UDINT; (* File date (Epoch) *)
    FName : STRING[ 64 ]; (* File name *)
    Threshold : USINT; (* File number threshold *)
    Dir : STRING[ 32 ]; (* Directory name *)
    DirWithFilter : STRING[ 32 ]; (* Directory name with filter *)
END_VAR

// *****************************************************************************
// PROGRAM "ST_DeleteOldestFiles"
// *****************************************************************************
// If set by debug the "Delete" variable the program maintains a defined number
// of files into a directory. If there are more than defined the oldest are
// deleted.
// -----------------------------------------------------------------------------

    // -------------------------------------------------------------------------
    // PROGRAM INITIALIZATION
    // -------------------------------------------------------------------------
    // Execute initializations.

    IF (SysFirstLoop) THEN
        Threshold:=2; //File number threshold
        Dir:='C:/MyDir'; //Directory to list
        DirWithFilter:=CONCAT(Dir, '/*.*'); //Directory to list with filter to get all its files
        DList.PathName:=ADR(DirWithFilter); //Directory to list
    END_IF;

    // -------------------------------------------------------------------------
    // EXECUTE THE CONTROL
    // -------------------------------------------------------------------------
    // Check if command set.

    IF NOT(Delete) THEN
        CaseNr:=0; //Program case
    ELSE

        // Manage the directory listing.

        DList(); //Directory listing
        DList.Init:=FALSE; //Init listing
        DList.Next:=FALSE; //Next command

        // ---------------------------------------------------------------------
        // PROGRAM CASES
        // ---------------------------------------------------------------------
        // Program case management.

        CASE (CaseNr) OF

            // -----------------------------------------------------------------
            // Init directory listing.

            0:
            FFound:=0; //Files found
            FDate:=SysDateTime; //File date (Epoch)
            DList.Init:=TRUE; //Init listing
            CaseNr:=CaseNr+1; //Program case

            // -----------------------------------------------------------------
            // If file found returns file data.

            1:
            IF NOT(DList.Found) THEN CaseNr:=CaseNr+1; RETURN; END_IF;
            FFound:=FFound+1; //Files found
            DList.Next:=TRUE; //Next command

            // Check if file date is older previous.

            IF (DList.Time > FDate) THEN RETURN; END_IF;
            FDate:=DList.Time; //File date (Epoch)
            i:=SysVsnprintf(ADR(FName), SIZEOF(FName), ADR('%s'), STRING_TYPE, ADR(Dir));
            i:=SysCVsnprintf(ADR(FName), SIZEOF(FName), ADR('/%s'), STRING_TYPE, DList.Name);

            // -----------------------------------------------------------------
            // If number of files in directory is greater than the threshold,
            // the oldest is deleted.

            2:
            IF (FFound <= Threshold) THEN Delete:=FALSE; RETURN; END_IF;
            i:=SysFileRemove(ADR(FName)); //Delete file
            CaseNr:=0; //Program case
        END_CASE;
    END_IF;

// [End of file]
Esse artigo foi útil?