Este bloque de funciones de ejecutar en tarea Atrás, devuelve información sobre archivos o directorios individuales o sobre archivos o directorios contenidos en un directorio. pasando en PathNane el nombre completo del archivo o directorio de la ruta y activando Init, si el archivo o directorio está presente, se devuelve la información.
Listar todos los archivos en una carpeta
Al definir en PathName el nombre de una carpeta seguido del filtro “/*.*”, activando Init la lista de archivos se inicializa y se devuelve el primer archivo encontrado. En cada comando Next se realiza una búsqueda de un nuevo archivo, si se encuentra el archivo de salida Found se activa para un bucle y su nombre se devuelve a Name. Finalizó la lista de todos los archivos presentes en el comando Next la salida ya no está activada Found e Name está listado.
También es posible realizar un filtro sobre los archivos a devolver. Por ejemplo, al usar “/*.htm” solo se devuelven los archivos con la extensión “htm”. La salida IsDir se activa si el nombre del archivo devuelto es el de un subdirectorio
Reemplaza SysDirListing
Reemplaza el bloque de funciones SysDirListing, cambiando el tipo de parámetros de entrada y salida de cadena a puntero de cadena. La declaración 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;
Se convierte en:
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;
Función de bloqueo
CÓDIGOS: indisponible
Laboratorio lógico: eLLabXUnified12Lib
Descripción
Init (BOOL) Tras la activación, se inicializa el índice de los archivos en el directorio indicado y se devuelve el nombre del primer archivo encontrado.
Next (BOOL) Tras la activación, se devuelve el nombre del archivo apuntado por el índice en el directorio indicado. El índice se incrementa apuntando al siguiente archivo.
PathName (@STRING) Nombre del archivo completo con ruta.
Para detectar los datos de un archivo específico, defina su ruta y nombre, por ejemplo C:\MyDir\MyFile.log.
Para detectar los datos de un directorio, defina su ruta de ejemplo C:\MyDir\MyFile.log.
Para enumerar archivos en un directorio, defina la ruta con el filtro de ejemplo C:\MyDir\*.log.
Found (BOOL) Se activa para un bucle si se le ordena Init o Next Se encontró un archivo.
Fault (BOOL) Se activa para un bucle si hay un error de ejecución.
IsDir (BOOL) Activo si el nombre de archivo devuelto pertenece a un subdirectorio.
Size (UDINT) Tamaño del archivo.
FTime (UDINT) Fecha de última modificación del archivo en tiempo Epoch (UTC).
Name (@STRING) Nombre de archivo incluyendo cualquier extensión
Ejemplos
ST_SysGetFileInfos: Al conectarse en telnet al puerto indicado, se devuelve el final de los archivos y directorios que se encuentran en la ruta establecida.
ST_DeleteOldestFiles: Activando la variable de depuración Delete, se comprueban los archivos en el directorio definido y se eliminan los más antiguos para mantener el número total de archivos igual al valor de Threshold.
Otros ejemplos se encuentran en la función Sysremove.
Laboratorio lógico (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]
Laboratorio lógico (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]