Unit CastleFilesUtils
Description
Operations on files.
Includes functions to help cross-platform programs to know where to read/write files:
ApplicationConfig – user config files
Hints about what to use (and what not to use) in a cross-platform applications using Castle Game Engine:
To get a nice application name, use the
ApplicationName
function (defined in the standard SysUtils unit for FPC, or CastleUtils unit for Delphi). Every application can customize it by assigning OnGetApplicationName or (often more comfortable) assigning ApplicationProperties.ApplicationName. The Castle Game Engine units use it where appropriate.Use URLs for everything. See https://castle-engine.io/manual_network.php .
Use "castle-data:/xxx" URLs to refer to the data directory of your project. See https://castle-engine.io/data . For example:
MyImage := LoadImage('castle-data:/gui/my_image.png');
Use the ApplicationConfig for all URLs where you save or load the user configuration files, savegames etc.
Do not try to get the application name, or executable file name, using ParamStr(0). Do not rely on Lazarus Application.ExeName or our own (deprecated) ExeName.
The "executable file name" is just not 100% reliably available on all OSes. And in some cases, like Android or iOS, the concept of "executable file name" doesn't even make sense, as your application is a library being called by a higher-level application (written in Java or Objective-C), and it's really an "internal matter" where is the executable file that started it.
Use CastleFindFiles unit to search for files and directories. It nicely works with URLs, has some support for the Android "assets" filesystem, and it has more comfortable API (e.g. searching recursively or not is just a matter of passing a particular flag).
Do not use standard FindFirst/FindNext.
Read and write all data using streams (TStream) descendants. Open and save these streams using our CastleDownload unit.
Uses
- BaseUnix
- Unix
- SysUtils
- CastleUtils
Overview
Classes, Interfaces, Objects and Records
Name | Description |
---|---|
Class EExeNameNotAvailable |
|
Class ERemoveFailed |
Functions and Procedures
function ExeName: string; deprecated 'as this function is not portable (may raise exception on non-Windows), it should not be used in a cross-platform game code'; |
function ProgramName: string; deprecated; |
function RegularFileExists(const FileName: String): Boolean; |
function NormalFileExists(const FileName: String): Boolean; deprecated 'use RegularFileExists'; |
function UserConfigPath: string; deprecated; |
function UserConfigFile(const Extension: string): string; deprecated; |
function ApplicationConfig(const Path: string): string; |
function ApplicationData(const Path: String): String; deprecated 'use ''castle-data:/xxx'' instead of ApplicationData(''xxx'')'; |
function HomePath: string; |
function ExpandHomePath(const FileName: string): string; |
procedure CheckDeleteFile(const FileName: string; const Warn: Boolean = false); |
procedure CheckRemoveDir(const DirFileName: string; const Warn: Boolean = false); |
procedure CheckForceDirectories(const Dir: string); |
procedure CheckCopyFile(const Source, Dest: string); |
procedure CheckRenameFile(const Source, Dest: string); |
procedure RemoveNonEmptyDir(const DirName: string; const Warn: Boolean = false); |
procedure CopyDirectory(SourcePath, DestinationPath: string); |
function FileNameAutoInc(const UrlPattern: string): string; overload; |
function FileNameAutoInc(const UrlPrefix, UrlSuffixWithPattern: string): string; overload; |
function FnameAutoInc(const UrlPattern: string): string; deprecated 'use FileNameAutoInc'; |
function ParentPath(DirName: string; DoExpandDirName: Boolean = true): string; deprecated 'use URLs and operate on them using CastleUriUtils unit'; |
function CombinePaths(BasePath, RelPath: string): string; |
Function PathFileSearch(Const Name : String; ImplicitCurrentDir : Boolean = True) : String; |
function FindExe(const ExeName: string): string; |
function AddExeExtension(const ExePath: string): string; |
function GetTempFileNameCheck: string; |
function GetTempFileNamePrefix: string; |
function FileToString(const Url: String; out MimeType: string): AnsiString; overload; |
function FileToString(const Url: String): AnsiString; overload; |
procedure StringToFile(const Url: String; const Contents: AnsiString); |
function SaveScreenPath: String; |
function DirectorySize(const Dir: String): QWord; |
Variables
ApplicationConfigOverride: string; |
ApplicationDataOverride: string; |
Description
Functions and Procedures
function ExeName: string; deprecated 'as this function is not portable (may raise exception on non-Windows), it should not be used in a cross-platform game code'; |
Warning: this symbol is deprecated: as this function is not portable (may raise exception on non-Windows), it should not be used in a cross-platform game code Full (absolute) FileName to executable file of this program. If it's impossible to obtain, raises exception EExeNameNotAvailable. Under Windows this is simply ParamStr(0) (and it never raises exception), but under other OSes it's not so simple to obtain (although it's important to note that usually programs under UNIX should not need this, actually). Internal implementation notes: Under UNIXes other than Linux I don't know how to obtain this, so e.g. under FreeBSD this will always raise an exception. Under Linux I'm trying to read file /proc/getpid()/exe, this should work under most Linuxes as long as user compiled Linux kernel with /proc support. So under Linux this may work, but still you should be always prepared that it may raise EExeNameNotAvailable. |
function ProgramName: string; deprecated; |
Warning: this symbol is deprecated. The name of our program. Deprecated, this is equivalent to ApplicationName, and you should just call ApplicationName directly in new code. ApplicationName is included in standard FPC SysUtils unit for FPC, has good default and is easily configurable by callback OnGetApplicationName or our ApplicationProperties.ApplicationName. See http://www.freepascal.org/docs-html/rtl/sysutils/getappconfigdir.html . This is suitable to show to user. It should also indicate how to run the program, usually it should be the basename of the executable (although we do not depend on it technically). It may be used to derive config file/dir for our program, see ApplicationConfig. |
function RegularFileExists(const FileName: String): Boolean; |
Returns Detects and returns Returns Consider using UriExists or UriFileExists instead of this function, since in CGE you should use URLs for everything. |
function NormalFileExists(const FileName: String): Boolean; deprecated 'use RegularFileExists'; |
Warning: this symbol is deprecated: use RegularFileExists This item has no description. |
function UserConfigPath: string; deprecated; |
Warning: this symbol is deprecated. Path to store user configuration files. This is some directory that should be writeable and that is a standard directory under this OS to put user config files. Always returns absolute (not relative) path. Result contains trailing PathDelim. Deprecated, use ApplicationConfig instead. |
function UserConfigFile(const Extension: string): string; deprecated; |
Warning: this symbol is deprecated. Filename to store user configuration. Always returns absolute (not relative) path. Returns FileName that:
Deprecated, use ApplicationConfig(ApplicationName + Extension) instead. |
function ApplicationConfig(const Path: string): string; |
URL where we should read and write configuration files. This always returns a Given Path specifies a name of the file (with possible subdirectories) under the user config directory. The Path is a relative URL, so you should always use slashes (regardless of OS), and you can escape characters by %xx. We make sure that the directory (including the subdirectories you specify in Path) exists, creating it if necessary. But we do not create the file. We should have permissions to write inside the given directory (although, as always on multi-process OS, the only 100% way to know if you can write there is to actually try it). This uses FPC GetAppConfigDir under the hood. Which in turn looks at ApplicationName, and may use OS-specific algorithm to find good config directory, see http://www.freepascal.org/docs-html/rtl/sysutils/ongetapplicationname.html . On UNIX this follows XDG Base Directory Specification, see http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html (simplifying: looks inside ~/.config/<application-name>/). |
function ApplicationData(const Path: String): String; deprecated 'use ''castle-data:/xxx'' instead of ApplicationData(''xxx'')'; |
Warning: this symbol is deprecated: use 'castle-data:/xxx' instead of ApplicationData('xxx') This item has no description. |
function HomePath: string; |
User's home directory, with trailing PathDelim. Taken from environment variable $HOME, unless it's empty or unset, in which case we take this from Unix user database by real uid. This is what bash does (more-or-less, when home directory does not exist strange things happen), that's what programs should do according to `info libc' and Kambi preferences. |
function ExpandHomePath(const FileName: string): string; |
Expand tilde (~) in path, just like shell. Expands ~ to ExclPathDelim(HomePath) under UNIX. Under Windows, does nothing. |
procedure CheckDeleteFile(const FileName: string; const Warn: Boolean = false); |
Remove file. Similar to standard DeleteFile, but this checks result and raises exception or makes a warning (see Warn parameter) in case of trouble When Warn = Exceptions raised
|
procedure CheckRemoveDir(const DirFileName: string; const Warn: Boolean = false); |
Remove empty directory. Similar to standard RemoveDir, but this checks result and raises exception or makes a warning (see Warn parameter) in case of trouble. When Warn = Exceptions raised
|
procedure CheckForceDirectories(const Dir: string); |
Make sure directory exists, eventually creating it and all directories along the way. Similar to standard ForceDirectories, but this checks result and raises exception in case of trouble. |
procedure CheckCopyFile(const Source, Dest: string); |
Copy file from Source to Dest. The directory of Dest must already exist. File is overwritten unconditionally. |
procedure CheckRenameFile(const Source, Dest: string); |
Move file from Source to Dest. The directory of Dest must already exist. File is overwritten unconditionally. |
procedure RemoveNonEmptyDir(const DirName: string; const Warn: Boolean = false); |
Remove the directory DirName, recursively, unconditionally, with all the files and subdirectories inside. DirName may but doesn't have to end with PathDelim. In case of symlinks, removes the symlink (but does not descend inside, i.e. will not remove files inside a symlink to a directory). When Warn = Exceptions raised
|
procedure CopyDirectory(SourcePath, DestinationPath: string); |
Copies the contents from SourceDir to DestinationDir. DestinationDir and necessary subdirectories are created, if needed. Both SourceDir and DestinationDir may, but do not have to, end with PathDelim. Note that DestinationDir contents are not cleared here. In effect, the existing files (present in DestinationDir before the copy operation, and not overwritten by corresponding files in SourceDir) will be left. If you need to clear them, consider using if DirectoryExists(DestinationDir) then RemoveNonEmptyDir(DestinationDir); CopyDirectory(SourceDir, DestinationDir); |
function FileNameAutoInc(const UrlPattern: string): string; overload; |
Substitute We start with number = 0 and do Since we use standard Note that it's possible on every OS that some other program, or a second copy of your own program, will write to the resulting URL between FileNameAutoInc determined it doesn't exist and you opened the file. So using this cannot guarantee that you really always write to a new file – as always, be prepared for anything happening in parallel when dealing with a filesystem. The overloaded version with separate UrlPrefix and UrlSuffixWithPattern replaces Example usage to save a screenshot:
ScreenshotUrl := FileNameAutoInc(SaveScreenPath, 'screenshot_%d.png');
Note that to save a screenshot in the most cross-platform way possible, we advise using Window.Container.SaveScreenToDefaultFile instead, it will use SaveScreenPath or more elebarate mechanism to work on all platforms. Example usage to save anything else to user config:
SaveSomethingUrl := FileNameAutoInc(ApplicationConfig('save_something_%d.png'));
Note that it will be replaced soon by |
function FileNameAutoInc(const UrlPrefix, UrlSuffixWithPattern: string): string; overload; |
This item has no description. |
function FnameAutoInc(const UrlPattern: string): string; deprecated 'use FileNameAutoInc'; |
Warning: this symbol is deprecated: use FileNameAutoInc This item has no description. |
function ParentPath(DirName: string; DoExpandDirName: Boolean = true): string; deprecated 'use URLs and operate on them using CastleUriUtils unit'; |
Warning: this symbol is deprecated: use URLs and operate on them using CastleUriUtils unit Parent directory name. Given DirName may be absolute or relative. Given DirName may but doesn't have to include trailing PathDelim. Result is always absolute FileName, and contains trailing PathDelim. Returns the same DirName if there's no parent directory. When DoExpandDirName = false then it is assumed that DirName already is absolute path. Then this function is pure string-operation (no actual reading of any filesystem info), so it works faster and DirName does not need to exist. |
function CombinePaths(BasePath, RelPath: string): string; |
Combines BasePath with RelPath into complete path. BasePath may be an absolute path or relative path. Also RelPath may be an absolute path or relative path. If RelPath is absolute, result is just RelPath. Otherwise, result is path starting from BasePath with RelPath applied (whether the result is absolute or relative depends on whether BasePath was absolute or relative). Usually you should instead operate on URLs and combine them using CastleUriUtils.CombineURI. |
Function PathFileSearch(Const Name : String; ImplicitCurrentDir : Boolean = True) : String; |
Search a file on $PATH. Works with double quotes around components of path list, avoiding this bug: http://bugs.freepascal.org/view.php?id=19279. See http://www.freepascal.org/docs-html/rtl/sysutils/filesearch.html for original FileSearch docs. In FPC >= 2.5.1, you should instead use just ExeSearch(Name). It also will use $PATH and avoid double quotes problems on Windows. See http://bugs.freepascal.org/view.php?id=19282 and fix on http://svn.freepascal.org/cgi-bin/viewvc.cgi?view=rev&revision=17717 . |
function FindExe(const ExeName: string): string; |
Find program on $PATH. Automatically adds ExeExtension, so don't add it yourself. On Windows, may also add alternative executable extensions (.com, .bat, .cmd). Searches in $PATH (and, if OS does this, in current directory — this is standard on Windows but not on Unix). Returns '' (if not found) or absolute FileName. |
function AddExeExtension(const ExePath: string): string; |
Add an exe file extension, searching for an existing file starting with ExePath. On non-Windows, this is just equal to ExePath + ExeExtension, which in practice is just equal to ExePath (since ExeExtension is empty on Unix). But on Windows, this tries to append other extensions (.com, .bat, .cmd, just like FindExe), depending on what file exists. |
function GetTempFileNameCheck: string; |
Get temporary FileName, suitable for ApplicationName, checking that it doesn't exist. |
function GetTempFileNamePrefix: string; |
Return a prefix (beginning of an absolute FileName) to save a series of temporary files. |
function FileToString(const Url: String; out MimeType: string): AnsiString; overload; |
Read file or URL contents to a string. MimeType is returned, calculated just like the Download function. |
function FileToString(const Url: String): AnsiString; overload; |
This item has no description. |
procedure StringToFile(const Url: String; const Contents: AnsiString); |
This item has no description. |
function SaveScreenPath: String; |
Recommended path where to put screenshots on the current platform. Always ends with PathDelim and returns a directory that exists. Empty string means that we cannot recommend any safe path to store screenshots (on some platforms, like mobile or console, it's not so easy to just store a file in the filesystem, without any permissions; and on some platforms they may have special API for this stuff). |
function DirectorySize(const Dir: String): QWord; |
Calculate size of all files in this dir. |
Variables
ApplicationConfigOverride: string; |
URL used as a prefix of all ApplicationConfig returned URLs. This overrides any autodetection of a suitable "user config" directory done by default by ApplicationConfig. This must always end with a slash, if it's not empty. |
ApplicationDataOverride: string; |
URL used as the base application data directory. Overrides the platform-specific autodetection of this directory. See data directory documentation. If it's not empty, this must always end with a slash. This cannot start with 'castle-data:/...', since it would mean that ResolveCastleDataUrl can never finish its job. |
Generated by PasDoc 0.16.0-snapshot.