Package DE_EPAGES::Core::API::File
This module provides file and directory access.
Functions
- AbsolutePath
- BackupDirectory
- BackupFile
- CompareDirectories
- CompareMD5File
- CompareMD5TextFile
- ConvertPathChars
- CopyDirectory
- CopyFile
- CorrectPathSlashes
- CreateDirectory
- DeleteDirectory
- DeleteFile
- DeleteListedFiles
- DeleteStaticAtDirectory
- DetectFileEncoding
- ExistsDirectory
- ExistsFile
- ExistsFileCaseSensitive
- FilesOnlyInDir1
- GetAccessRights
- GetBOM
- GetCachedFile
- GetDOSReadOnlyFiles
- GetDirectorySize
- GetExecBit
- GetFileContent
- GetFileContentLines
- GetFileInfo
- GetFileMD5Digest
- GetFileNames
- GetFileSize
- GetInfoDirectory
- GetSimilarFileName
- GetSubDirectories
- GetTrashRoot
- IsFileNewer
- IsImageFile
- IsInPath
- IsTextFile
- LockFile
- MakePathReadable
- MakePathWriteable
- MergeIniFiles
- MoveFile
- PathGlob2TypeGlob
- RealPath
- RebuildDirectory
- RebuildFile
- RelativePath
- RenameDirectory
- ResolveSymbolicLink
- RunOnDirectory
- SetAccessRights
- SetPosixACLs
- Text2Dos
- Text2Unix
- WindowsPath
- WriteFile
- _GetOSErrorMessage
- fsplit
AbsolutePath
Converts paths like 'sub1/sub2' to 'C:/sub1/sub2'.
Syntax |
$DetPath = AbsolutePath($Path); |
Input |
|
Return |
|
BackupDirectory
Copies files which exist in both, source directory and target directory, but not in the backup directory from the target directory to the backup directory.
Syntax |
BackupDirectory( $SourceDir, $TargetDir, $BackupDir, $Flags ); |
Input |
|
BackupFile
If BackupFile doesn't exist and SourceFile and TargetFile are not equal this function copies TargetFile to BackupFile.
Syntax |
BackupFile( $SourceFile, $TargetFile, $BackupFile ); |
Input |
|
CompareDirectories
Compares contents (file names) of two directories.
Syntax |
$Compare = CompareDirectories($Path1, $Path2); |
Input |
|
Return |
|
CompareMD5File
if it is a TextFile IsTextFile returns CompareMD5TextFile($File, $MD5Digest); else returns true if GetFileMD5Digest eq $MD5Digest
Syntax |
$IsEqual = CompareMD5File($File, $MD5Digest); |
Example |
$IsEqual = CompareMD5File('testtemp.txt','4c832c34a88de899dab3d00b7ccca632'); |
Input |
|
Return |
|
CompareMD5TextFile
returns 1 if the MD5Hash of the file content, or the MD5Hash of the dos2unix converted file content or the MD5Hash of the unix2dos converted file content is equal $MD5Digest
Syntax |
$IsEqual = CompareMD5TextFile($File, $MD5Digest); |
Example |
$IsEqual = CompareMD5TextFile('testtemp.txt','4c832c34a88de899dab3d00b7ccca632'); |
Input |
|
Return |
|
ConvertPathChars
Encodes a normal string to a string, which can be used as direcory name. The following characters are converted to a 4-digit hex code surrounded by underline: \ / : * ? " <> | & ' % # . \x{0000}-\x{0020} \x{0080}-\x{ffff} For example: '.' -> '_002E_' Note on dots in file names: Windows silently removes a trailing dot from directry or file names. UrlScan for IIS rejects all directory names containing dots.
Syntax |
$DirectoryName = ConvertPathChars( $Alias ); |
Example |
$DirectoryName = ConvertPathChars( "IBN-08/25.1234" ); |
Input |
|
CopyDirectory
Copies all files from one directory to another. This function works recursively and creates the necessary sub directories. If a file already exists in the target directory, then it will be saved in the backup directory unless there is already a backup file. In this case the target file is overwritten by the source file. The source directory must exist. The target and backup directories will be created if they don't exist.
Syntax |
CopyDirectory( $SourceDir, $TargetDir, $BackupDir, $Flags ); |
Example |
CopyDirectory( "c:\\Temp","d:\\Temp", "e:\\backup", { recursive => 1 } ); |
Input |
|
CopyFile
Copies a file in binary mode and sets the access rights.
Syntax |
CopyFile( $Source, $Target, $hFlags ); |
Input |
|
CorrectPathSlashes
Replaces slashes and back-slashes to unix/windows specific concatenation.
Syntax |
$CorrectedPath = CorrectPathSlashes($AnyPath); |
Input |
|
Return |
|
CreateDirectory
Creates the directory path. Does nothing if the directory already exists.
Syntax |
$CountCreated = CreateDirectory($Path, $hFlags); |
Example |
$CountCreated = CreateDirectory('C:\\Test', {'recursive'=>0,'ExecBit'=>1}); |
Input |
|
Return |
|
DeleteDirectory
Removes the directory. Throws an error if the directory cannot be deleted, for example because it contains files or sub directories and the recursive flag is not set. If the directory did not exist before, then the function does nothing.
Syntax |
$Deleted = DeleteDirectory($Path, $hFlags); |
Example |
$Deleted = DeleteDirectory('C:\\Test',{'recursive' => 1}); |
Input |
|
Return |
|
DeleteFile
Removes a file from disk. The function throws an error if the file cannot be deleted. If the file did not exist before, the function does nothing. ErrorCodes:
- FILE_REMOVE_FAILED
Syntax |
$Deleted = DeleteFile($FileName); |
Example |
DeleteFile("/var/log/error.log"); |
Input |
|
Return |
|
DeleteListedFiles
Removes listed files from patch. If an entry ends in .inexistent assume this as a file file to be handled by DeleteListedFiles. The function throws an error if a file cannot be deleted. If the file did not exist before, the function does nothing.
Syntax |
$Deleted = DeleteListedFiles($Path, $FileList); |
Example |
$Deleted = DeleteListedFiles('C:\\Test','Test.inexistent'); |
Input |
|
Return |
|
DeleteStaticAtDirectory
Removes _STATIC_ directories in given directory.
Syntax |
DeleteStaticAtDirectory($Directory); |
Input |
|
DetectFileEncoding
Checks if the file has a BOM marker (Unicode Byte Order Mark) and retruns the corresponding encoding, for example 'utf-8' or 'utf-7'. Returns undef if the file does not have a BOM.
Syntax |
$Encoding = DetectFileEncoding( $FileName ); |
Input |
|
Return |
|
ExistsDirectory
Returns true if the directory exists.
Syntax |
$Exists = ExistsDirectory($Path); |
Example |
if( ExistsDirectory('C:\\Test') ) { ... } |
Input |
|
Return |
|
ExistsFile
Returns true if the file exits.
Syntax |
$Exists = ExistsFile($FileName); |
Example |
if( ExistsDirectory('C:\\Test\\test.txt') ) { ... } |
Input |
|
Return |
|
ExistsFileCaseSensitive
Returns true if the file exits. Under windows filenames are not case sensitive, this function is needed to guarantee equal behavior for all operating systems. Now these file "tEsT.XmL" is no longer found under windows.
Syntax |
$Exists = ExistsFileCaseSensitive($FileName); |
Example |
if( ExistsFileCaseSensitive('C:\\Test\\test.txt') ) { ... } |
Input |
|
Return |
|
FilesOnlyInDir1
Returns a list of files that exist in $Dir1, but not in $Dir2. This works with symbolic links.
Syntax |
$aFileList = FilesOnlyInDir1($Dir1, $Dir2); |
Input |
|
Output |
|
GetAccessRights
Returns ref.hash with mode, uid and gid for FileName (only unix).
Syntax |
$hAccess = GetAccessRights($FileName); |
Input |
|
Return |
|
GetBOM
Returns the Byte Order Mark for the given encoding.
Syntax |
$BOM = GetBOM( $Encoding ); |
Example |
$BOM = GetBOM( 'utf16be' ); |
Input |
|
Return |
|
GetCachedFile
Return the content of an file. If you call this function twice and the file was not changed the file wasnt read again. The up-to-dateness of the file will be tested each second.
Syntax |
$Content = GetCachedFile($FileName, $Sub); |
Example |
my $IniConfig = GetCachedFile( $CONFIG_FILENAME, sub { my ($FileName) = @_; return DE_EPAGES::Core::API::IniConfig->new( FileName => $FileName ); }); |
Input |
|
Return |
|
GetDOSReadOnlyFiles
Returns a ref.array of DOS files with read-only flag
Syntax |
$aReadOnlyFiles = GetDOSReadOnlyFiles($AnyPath); |
Input |
|
Return |
|
GetDirectorySize
Returns the size of a directory in bytes. If a block size is specified all file and directory sizes will be ceiled to multiple of block size. Note: On a windows system is the directory entry 0 bytes. ErrorCodes:
- DIRECTORY_NOT_FOUND
Syntax |
$Size = GetDirectorySize($Directory, $BlockSize); |
Example |
my $Size = GetDirectorySize("/var/log", 1024); |
Input |
|
Return |
|
GetExecBit
Returns ref.hash with execbit (only unix).
Syntax |
$hBits = GetExecBit($FileName); |
Input |
|
Return |
|
GetFileContent
Returns the content of a file as a scalar reference. ErrorCodes:
- FILE_NOT_FOUND
- FILE_OPEN_FAILED
- FILE_CLOSE_FAILED
Syntax |
$sContent = GetFileContent($FileName, $hFlags); |
Example |
my $sContent = GetFileContent("/var/log/error.log"); |
Input |
|
Return |
|
GetFileContentLines
Returns the content of a file as an array of lines. ErrorCodes:
- FILE_NOT_FOUND
- FILE_OPEN_FAILED
- FILE_CLOSE_FAILED
Syntax |
$aContent = GetFileContentLines($FileName, $hFlags, $LineSep); |
Example |
my $aContent = GetFileContentLines("/var/log/error.log"); |
Input |
|
Return |
|
GetFileInfo
Returns file size, modification and access time of a file. Returns an empty has if the file does not exist.
Syntax |
$hFileInfo = GetFileInfo($FileName); |
Input |
|
Return |
|
GetFileMD5Digest
Returns the md5 hex digest of the content of a file
Syntax |
$HexDigest = GetFileMD5Digest($FileName); |
Example |
my $HexDigest = GetFileMD5Digest("/var/log/error.log"); |
Input |
|
Return |
|
GetFileNames
Returns filenames which are included in the given directory in an array reference.
Syntax |
$aFiles = GetFileNames( $DirPath, $hFlags ); |
Example |
$aFiles = GetFileNames( 'C:\\', {'recursive' => 1} ); |
Input |
|
Return |
|
GetFileSize
Returns the size of a file in bytes. ErrorCodes:
- FILE_NOT_FOUND
- FILE_STATISTIC_FAILED
Syntax |
$Size = GetFileSize($FileName); |
Example |
my $Size = GetFileSize("/var/log/error.log"); |
Input |
|
Return |
|
GetInfoDirectory
Returns all items of a directory like files, subdirectories or others (e.g. links).
Syntax |
$hInfo = GetInfoDirectory( $DirPath , $hFlags ); |
Example |
$hInfo = GetInfoDirectory( 'C:\\', { recursive => 1, ignore => $raIgnore } ); |
Input |
|
Return |
|
GetSimilarFileName
Returns a file name for a base file name, that does not exist in this directory. This is helpful, when a file has to be copied, but shall not overwrite an existing file.
Syntax |
$SimilarFileName = GetSimilarFileName($FileName); |
Example |
$SimilarFileName = GetSimilarFileName('C:\\Photos\\photo.jpg'); # $SimilarFileName is 'C:\\Photos\\photo1.jpg', if this does not exist |
Input |
|
Return |
|
GetSubDirectories
Returns subdirectories of the given directory in an array reference. Please note that the array doesn't contain the '.' and '..' directories.
Syntax |
$aSubDirs = GetSubDirectories($Directory, $hFlags); |
Example |
$aSubDirs = GetSubDirectories('C:\\', {'recursive' => 1}); |
Input |
|
Return |
|
GetTrashRoot
Get the EPAGES_STATIC EPAGES_STORES EPAGES_WEBROOT Environment for creating a trash root for this path
Syntax |
$TrashRoot = GetTrashRoot($Path); |
Example |
$TrashRoot = GetTrashRoot($Path); |
Input |
|
Return |
|
IsFileNewer
Checks if the target file is newer than the source file. If the source does not exist it throws the error 'FILE_NOT_FOUND'. If the target file does not exist or is older than this function it returns 'false' (0).
Syntax |
IsFileNewer($Source, $Target); |
Input |
|
IsImageFile
Checks if the file is an image file using the file extensions see DE_EPAGES::Core::API::Constants constant IMAGE_FILE_TYPES.
Syntax |
$IsImageFile = IsImageFile($FileName); |
Input |
|
Return |
|
IsInPath
Test if a file or directory is located at a base directory. @example $IsInPath = IsInPath('C:\Programs\epages\..\..\Windows\some.conf', 'C:\Programs\epages'); // false @example $IsInPath = IsInPath('C:\Programs\epages\..\some.conf', 'C:\Programs'); // true
Syntax |
$IsInPath = IsInPath($DirectoryOrFile, $BaseDirectory); |
Input |
|
Return |
|
IsTextFile
Checks if the file is a textfile using the file extensions see DE_EPAGES::Core::API::Constants constant TEXT_FILE_TYPES.
Syntax |
$IsTextFile = IsTextFile($FileName); |
Input |
|
Return |
|
LockFile
Locks a file and unlocks it at the end of the code block. There are 2 locking modes awailable:
- w - write or exclusive lock. Once this lock has been obtained by one process, no other process can read from or write to the file. Use this mode when writing to a file to prevent other processes from reading while writing is in progress and prevent multiple processes from writing simultanously to the same file
- r - read or shared lock. Prevents other processes from writing to the file. However, multiple processes can obtain read locks and read concurrently from the same file.
Syntax |
LockFile( $FileHandle, $Access, $cCode ); |
Example |
my $FileHandle; open( $FileHandle, ">>test.txt" ) or die "Can't open file: $!"; LockFile( $FileHandle, 'w', sub { # seek to the end of the file in case someone appended # while we were waiting... seek( $FileHandle, 0, 2 ) or die $!; print FILE, "...\n"; }); close $FileHandle or die $!; |
Input |
|
MakePathReadable
Returns existing part of $Path and makes it readable.
Syntax |
($ExistingMode, $ExistingPath) = MakePathReadable($Path); |
Input |
|
Return |
|
MakePathWriteable
Returns existing part of $Path and makes it writeable.
Syntax |
($ExistingMode, $ExistingPath) = MakePathWriteable($Path); ($ExistingMode, $ExistingPath) = MakePathWriteable($Path, $ReadOnly); |
Input |
|
Return |
|
MergeIniFiles
Adds sections from $Source to $Target if not yet exist in $Target. If $aSections are defined, adds parameters from $Source to $Target if not yet exist in $Target. Removes duplicate comments in $Target.
Syntax |
MergeIniFiles($Target, $Source); MergeIniFiles($Target, $Source, $aSections); MergeIniFiles($Target, $Source, $aSections, $hFlags); |
Example |
MergeIniFiles("$ENV{EPAGES_CONFIG}/Scheduler.conf", "$ENV{EPAGES_CARTRIDGES}/DE_EPAGES/Database/Data/Scheduler/Scheduler.conf", [ 'LOOPS' ], { 'replace' => 'parameters' } ); |
Input |
|
MoveFile
Moves a file on disk if file on same device rename was used. We don't use perlfunc rename because it may not work across file system boundaries.
Syntax |
MoveFile($SourceFile, $TargetFile, $hFlags); |
Example |
MoveFile("/var/log/error.log", "/var/logger/error.b1"); |
Input |
|
PathGlob2TypeGlob
Changes $Path from path glob (as a/*/z/??) to type glob (as a\/.+\/z\/..)
Syntax |
$Path = PathGlob2TypeGlob($Path) |
Input |
|
Output |
|
RealPath
Converts paths like 'C:/sub1/sub2/..' to 'C:/sub1'.
Syntax |
$DetPath = RealPath($Path); |
Input |
|
Return |
|
RebuildDirectory
Copies files which exist in the source and backup directory and have the same modification time in source and target from the backup to the target directory. Deletes the backup file if it was copied.
Syntax |
RebuildDirectory( $SourceDir, $TargetDir, $BackupDir, $Flags ); |
Input |
|
RebuildFile
Deletes TargetFile if TargetFile and SourceFile exist and are equal. Moves BackupFile to TargetFile if BackupFile exists.
Syntax |
RebuildFile( $SourceFile, $TargetFile, $BackupFile, $Flags ); |
Input |
|
RelativePath
Returns the relative path to get from $BasePath to $RelatingPath. All output slashes are converted to /.
Syntax |
$Path = RelativePath( $BasePath, $RelatingPath ); |
Example |
$Path = RelativePath( 'C:\Windows\System32', 'C:\Windows\Fonts'); # $Path == '../Fonts'; |
Input |
|
Output |
|
RenameDirectory
Returns true if the directory was renamed. Returns false if the source directory does not exist. Throws an error if the source directory exists, but could not be renamed.
Syntax |
$Renamed = RenameDirectory($Source, $Target); $Renamed = RenameDirectory($Source, $Target, $hFlags); |
Example |
RenameDirectory('C:\\Test\OldDirName','C:\\Test\NewDirName', { create_directory => 1 }); |
Input |
|
Return |
|
ResolveSymbolicLink
Returns resolved link of path if it exists, otherwise it returns path.
Syntax |
$ResolvedLink = ResolveSymbolicLink($Path); |
Input |
|
Return |
|
RunOnDirectory
execute the given function on specific folder and returns the result of given function.
Syntax |
$Result = RunOnDirectory($FolderName, $Sub); |
Example |
my $aOldFiles = RunOnDirectory($OldFolder, sub{ my $aFiles = GetFileNames( undef , {'recursive' => 1} ); return $aFiles; } ); |
Input |
|
Return |
|
SetAccessRights
Changes access rights (chmod and chown) for unix
fallbacks for undefined fields:
- UserID: get UID from User
- User: default owner (depends on path of $FileName)
- GroupID: get GID from Group
- Group: default group (depends on path of $FileName)
- ExecBit: -d $FileName ? 1 : 0
- Mode: default mode (depends on path of $FileName) plus ExecBit.
Does nothing if:
- function is executed under Windows
- $FileName does not exist
- none of $hFlags (UserID GroupID Mode aTime mTime) is defined AND
(stat eq ignore OR $FileName is outside of $EPAGES)
Syntax |
SetAccessRights($FileName, $hFlags); |
Input |
|
SetPosixACLs
Adds POSIX ACL permissions 'rwx' to user ep_appl on any file in $Path.
Does nothing if:
- function is executed under Windows
- environment variable EPAGES_ACL is unset/0
- $Path does not exist
- effective user is not 'root'
Syntax |
SetPosixACLs($Path); |
Input |
|
Text2Dos
Checks if text and moves newlines to UNIX style newlines.
Syntax |
Text2Dos($FileName, $Force); |
Input |
|
Text2Unix
Checks if text and moves newlines to UNIX style newlines.
Syntax |
Text2Unix($FileName, $Force); |
Input |
|
WindowsPath
Replaces slashes of an unix path with back-slashes.
Syntax |
$WindowsPath = WindowsPath($AnyPath); |
Input |
|
Return |
|
WriteFile
Writes a file to disk. Several options are accepted for modifying the write behaviour. ErrorCodes:
- FILE_OPEN_FAILED
- FILE_CLOSE_FAILED
Syntax |
WriteFile($FileName, $rContent, $hFlags); |
Example |
WriteFile("/var/log/error.log", \$Content, { binary=>1, create_directory=>1} ); |
Input |
|
_GetOSErrorMessage
Returns the operating-system specific error message of the last I/O operation. Uses Win32::FormatMessage() for Windows and $! otherwise.
Syntax |
$Message = _GetOSErrorMessage(); |
Example |
say _GetOSErrorMessage(); |
Output |
|
fsplit
This function splits a path into its parts, this works for unix and dos paths.
Parts, not present, are returned empty or undef.
Syntax |
($Path, $FileName, $Extension) = fsplit($FilePath); |
Example |
('/', 'roedel', '.txt') = fsplit('/roedel.txt');<br> ('/', 'roedel', undef ) = fsplit('/roedel');<br> ('.', 'roedel', '.txt') = fsplit('roedel.txt');<br> ('c:/epages', 'roedel', '.txt') = fsplit('c:/epages/roedel.txt'); ('\\server\share', 'roedel', '.txt') = fsplit('\\server\share\roedel.txt'); |
Input |
|
Return |
|