Axmol 3.0.0-89d6d9a
Loading...
Searching...
No Matches
FileUtils Class Referenceabstract

Helper class to handle file operations. More...

#include <FileUtils.h>

Inherited by FileUtilsWinRT.

Public Member Functions

virtual ~FileUtils ()
 The destructor of FileUtils.
virtual void purgeCachedEntries ()
 Purges full path caches.
virtual std::string getStringFromFile (std::string_view filename) const
 Gets string from a file.
virtual Data getDataFromFile (std::string_view filename) const
 Creates binary data from a file.
template<typename T, typename E = std::enable_if_t<tlx::is_resizable_container_v<T>>>
Status getContents (std::string_view filename, T *buffer) const
 Gets whole file contents as string from a file.
virtual std::string fullPathForFilename (std::string_view filename) const
 Returns the fullpath for a given filename.
virtual std::string fullPathFromRelativeFile (std::string_view filename, std::string_view relativeFile) const
 Gets full path from a file name and the path of the relative file.
virtual std::string fullPathForDirectory (std::string_view dirname) const
 Returns the fullpath for a given dirname.
template<typename _Range>
void setSearchPaths (_Range &&searchPaths)
 Sets the array of search paths.
const std::string & getDefaultResourceRootPath () const
 Get default resource root path.
void setDefaultResourceRootPath (std::string_view path)
 Set default resource root path.
void addSearchPath (std::string_view path, const bool front=false)
 Add search path.
virtual const std::vector< std::string > & getSearchPaths () const
 Gets the array of search paths.
virtual const std::vector< std::string > & getOriginalSearchPaths () const
 Gets the original search path array set by 'setSearchPaths' or 'addSearchPath'.
virtual std::string getWritablePath () const =0
 Gets the writable path that may not be in the format of an absolute path.
virtual std::string getNativeWritableAbsolutePath () const =0
 Gets the writable path in the native file-system format.
virtual void setWritablePath (std::string_view writablePath)
 Sets writable path.
virtual void setPopupNotify (bool notify)
 Sets whether to pop-up a message box when failed to load an image.
virtual bool isPopupNotify () const
 Checks whether to pop up a message box when failed to load an image.
virtual ValueMap getValueMapFromFile (std::string_view filename) const
 Converts the contents of a file to a ValueMap.
virtual ValueMap getValueMapFromData (const char *filedata, int filesize) const
 Converts the contents of a file to a ValueMap.
virtual bool writeToFile (const ValueMap &dict, std::string_view fullPath) const
 write a ValueMap into a plist file
virtual bool writeStringToFile (std::string_view dataStr, std::string_view fullPath) const
 write a string into a file
virtual bool writeDataToFile (const Data &data, std::string_view fullPath) const
 write Data into a file
virtual bool writeValueMapToFile (const ValueMap &dict, std::string_view fullPath) const
 write ValueMap into a plist file
virtual bool writeValueVectorToFile (const ValueVector &vecData, std::string_view fullPath) const
 write ValueVector into a plist file
virtual bool isFileExist (std::string_view filename) const
 Checks whether a file exists.
virtual bool isAbsolutePath (std::string_view path) const
 Checks whether the path is an absolute path.
virtual bool isDirectoryExist (std::string_view dirPath) const
 Checks whether the path is a directory.
virtual bool createDirectories (std::string_view dirPath) const
 Creates a directory.
virtual bool removeDirectory (std::string_view dirPath) const
 Removes a directory.
virtual bool removeFile (std::string_view filepath) const
 Removes a file.
virtual bool renameFile (std::string_view path, std::string_view oldname, std::string_view name) const
 Renames a file under the given directory.
virtual bool renameFile (std::string_view oldfullpath, std::string_view newfullpath) const
 Renames a file under the given directory.
virtual int64_t getFileSize (std::string_view filepath) const
 Retrieve the file size.
virtual std::vector< std::string > listFiles (std::string_view dirPath) const
 List all files in a directory.
virtual void listFilesRecursively (std::string_view dirPath, std::vector< std::string > *files) const
 List all files recursively in a directory.
const tlx::string_map< std::string > getFullPathCache () const
 Returns the full path cache.
const tlx::string_map< std::string > getFullPathCacheDir () const
 Returns the full path cache.
virtual bool isFileExistInternal (std::string_view filename) const =0
 Checks whether a file exists without considering search paths and resolution orders.
virtual bool isDirectoryExistInternal (std::string_view dirPath) const
 Checks whether a directory exists without considering search paths and resolution orders.
virtual std::unique_ptr< IFileStream > openFileStream (std::string_view filePath, IFileStream::Mode mode) const
 Open a FileStream based on the implementation provided in openFileStream or its overrides.
bool copyFile (std::string_view sourcePath, std::string_view destinationPath, int64_t bufferSize=-1)
 Copy a file from source to destination.

Static Public Member Functions

static FileUtils * getInstance ()
 Gets the instance of FileUtils.
static void destroyInstance ()
 Destroys the instance of FileUtils.
static void setDelegate (FileUtils *delegate)
 You can inherit from platform dependent implementation of FileUtils, such as FileUtilsAndroid, and use this function to set delegate, then FileUtils will invoke delegate's implementation.
static bool writeXmlDocToFile (const pugi::xml_document &xmlDoc, std::string_view fullPath)
 save xml document to file
static bool writeBinaryToFile (const void *data, size_t dataSize, std::string_view fullPath)
 save data to file
static std::string getPathExtension (std::string_view filePath)
 Gets filename extension is a suffix (separated from the base filename by a dot) in lower case.

Detailed Description

Helper class to handle file operations.

Constructor & Destructor Documentation

◆ ~FileUtils()

virtual ~FileUtils ( )
virtual

The destructor of FileUtils.

@lua NA

Member Function Documentation

◆ setDelegate()

void setDelegate ( FileUtils * delegate)
static

You can inherit from platform dependent implementation of FileUtils, such as FileUtilsAndroid, and use this function to set delegate, then FileUtils will invoke delegate's implementation.

For example, your resources are encrypted, so you need to decrypt it after reading data from resources, then you can implement all getXXX functions, and engine will invoke your own getXX functions when reading data of resources.

If you don't want to system default implementation after setting delegate, you can just pass nullptr to this function.

Warning
It will delete previous delegate @lua NA

◆ getDataFromFile()

virtual Data getDataFromFile ( std::string_view filename) const
virtual

Creates binary data from a file.

Returns
A data object.

◆ getContents()

template<typename T, typename E = std::enable_if_t<tlx::is_resizable_container_v<T>>>
Status getContents ( std::string_view filename,
T * buffer ) const
inline

Gets whole file contents as string from a file.

Unlike getStringFromFile, these getContents methods:

  • read file in binary mode (does not convert CRLF to LF).
  • does not truncate the string when '\0' is found (returned string of getContents may have '\0' in the middle.).

The template version of can accept ax::Data, std::basic_string and std::vector.

std::string sbuf;
FileUtils::getInstance()->getContents("path/to/file", &sbuf);
std::vector<int> vbuf;
FileUtils::getInstance()->getContents("path/to/file", &vbuf);
Data dbuf;
FileUtils::getInstance()->getContents("path/to/file", &dbuf);
static FileUtils * getInstance()
Gets the instance of FileUtils.
Status getContents(std::string_view filename, T *buffer) const
Gets whole file contents as string from a file.
Definition FileUtils.h:200

Note: if you read to std::vector<T> and std::basic_string<T> where T is not 8 bit type, you may get 0 ~ sizeof(T)-1 bytes padding.

  • To write a new buffer class works with getContents, just extend ResizableBuffer.
  • To write a adapter for existing class, write a specialized ResizableBufferAdapter for that class, see follow code.
NS_AX_BEGIN // ResizableBufferAdapter needed in axmol namespace.
template<>
class ResizableBufferAdapter<AlreadyExistsBuffer> : public ResizableBuffer {
public:
ResizableBufferAdapter(AlreadyExistsBuffer* buffer) {
// your code here
}
void resize_and_overwrite(size_t num_of_bytes, std::function<size_t(void*, size_t)> op) override {
// your code here
}
size_t size_in_bytes() const override {
// your code here
}
NS_AX_END
Parameters
[in]filenameThe resource file name which contains the path.
[out]bufferThe buffer where the file contents are store to.
Returns
Returns:
  • Status::OK when there is no error, the buffer is filled with the contents of file.
  • Status::NotExists when file not exists, the buffer will not changed.
  • Status::OpenFailed when cannot open file, the buffer will not changed.
  • Status::ReadFailed when read end up before read whole, the buffer will fill with already read bytes.
  • Status::NotInitialized when FileUtils is not initializes, the buffer will not changed.
  • Status::TooLarge when there file to be read is too large (> 2^32-1), the buffer will not changed.
  • Status::ObtainSizeFailed when failed to obtain the file size, the buffer will not changed.

◆ fullPathForFilename()

virtual std::string fullPathForFilename ( std::string_view filename) const
virtual

Returns the fullpath for a given filename.

First it will try to get a new filename from the "filenameLookup" dictionary. If a new filename can't be found on the dictionary, it will use the original filename. Then it will try to obtain the full path of the filename using the FileUtils search rules: resolutions, and search paths. The file search is based on the array element order of search paths and resolution directories.

For instance:

We set two elements("/mnt/sdcard/", "internal_dir/") to search paths vector by setSearchPaths,

If we have a file named 'sprite.png', the mapping in fileLookup dictionary contains key: sprite.png -> value: sprite.pvr.gz. Firstly, it will replace 'sprite.png' with 'sprite.pvr.gz', then searching the file sprite.pvr.gz as follows:

    /mnt/sdcard/resources-ipadhd/sprite.pvr.gz      (if not found, search next)
    /mnt/sdcard/resources-ipad/sprite.pvr.gz        (if not found, search next)
    /mnt/sdcard/resources-iphonehd/sprite.pvr.gz    (if not found, search next)
    /mnt/sdcard/sprite.pvr.gz                       (if not found, search next)
    internal_dir/resources-ipadhd/sprite.pvr.gz     (if not found, search next)
    internal_dir/resources-ipad/sprite.pvr.gz       (if not found, search next)
    internal_dir/resources-iphonehd/sprite.pvr.gz   (if not found, search next)
    internal_dir/sprite.pvr.gz                      (if not found, return "sprite.png")

If the filename contains relative path like "gamescene/uilayer/sprite.png", and the mapping in fileLookup dictionary contains key: gamescene/uilayer/sprite.png -> value: gamescene/uilayer/sprite.pvr.gz. The file search order will be:

    /mnt/sdcard/gamescene/uilayer/resources-ipadhd/sprite.pvr.gz      (if not found, search next)
    /mnt/sdcard/gamescene/uilayer/resources-ipad/sprite.pvr.gz        (if not found, search next)
    /mnt/sdcard/gamescene/uilayer/resources-iphonehd/sprite.pvr.gz    (if not found, search next)
    /mnt/sdcard/gamescene/uilayer/sprite.pvr.gz                       (if not found, search next)
    internal_dir/gamescene/uilayer/resources-ipadhd/sprite.pvr.gz     (if not found, search next)
    internal_dir/gamescene/uilayer/resources-ipad/sprite.pvr.gz       (if not found, search next)
    internal_dir/gamescene/uilayer/resources-iphonehd/sprite.pvr.gz   (if not found, search next)
    internal_dir/gamescene/uilayer/sprite.pvr.gz                      (if not found, return

"gamescene/uilayer/sprite.png")

If the new file can't be found on the file system, it will return the parameter filename directly.

This method was added to simplify multiplatform support. Whether you are using cocos2d-js or any cross-compilation toolchain like StellaSDK or Apportable, you might need to load different resources for a given file in the different platforms.

Since
v2.1

◆ fullPathFromRelativeFile()

virtual std::string fullPathFromRelativeFile ( std::string_view filename,
std::string_view relativeFile ) const
virtual

Gets full path from a file name and the path of the relative file.

Parameters
filenameThe file name.
relativeFileThe path of the relative file.
Returns
The full path. e.g. filename: hello.png, pszRelativeFile: /User/path1/path2/hello.plist Return: /User/path1/path2/hello.pvr (If there a a key(hello.png)-value(hello.pvr) in FilenameLookup dictionary. )

◆ fullPathForDirectory()

virtual std::string fullPathForDirectory ( std::string_view dirname) const
virtual

Returns the fullpath for a given dirname.

Since
3.17.1

◆ setSearchPaths()

template<typename _Range>
void setSearchPaths ( _Range && searchPaths)
inline

Sets the array of search paths.

You can use this array to modify the search path of the resources. If you want to use "themes" or search resources in the "cache", you can do it easily by adding new entries in this array.

Note
This method could access relative path and absolute path. If the relative path was passed to the vector, FileUtils will add the default resource directory before the relative path. For instance: On Android, the default resource root path is "assets/". If "/mnt/sdcard/" and "resources-large" were set to the search paths vector, "resources-large" will be converted to "assets/resources-large" since it was a relative path.
Parameters
searchPathsThe array contains search paths.
See also
fullPathForFilename(const char*)
Since
v2.1 In js:var setSearchPaths(var jsval); @lua NA

◆ addSearchPath()

void addSearchPath ( std::string_view path,
const bool front = false )

Add search path.

Since
v2.1

◆ getSearchPaths()

virtual const std::vector< std::string > & getSearchPaths ( ) const
virtual

Gets the array of search paths.

Returns
The array of search paths which may contain the prefix of default resource root path.
Note
In best practise, getter function should return the value of setter function passes in. But since we should not break the compatibility, we keep using the old logic. Therefore, If you want to get the original search paths, please call 'getOriginalSearchPaths()' instead.
See also
fullPathForFilename(const char*). @lua NA

◆ getOriginalSearchPaths()

virtual const std::vector< std::string > & getOriginalSearchPaths ( ) const
virtual

Gets the original search path array set by 'setSearchPaths' or 'addSearchPath'.

Returns
The array of the original search paths

◆ getWritablePath()

virtual std::string getWritablePath ( ) const
pure virtual

Gets the writable path that may not be in the format of an absolute path.

Returns
The path that can be write/read a file in
Note
This may return the same value as getNativeWritableAbsolutePath(). If you require the absolute path to the underlying file system, then call getNativeWritableAbsolutePath() instead.

Implemented in FileUtilsWinRT.

◆ getNativeWritableAbsolutePath()

virtual std::string getNativeWritableAbsolutePath ( ) const
pure virtual

Gets the writable path in the native file-system format.

Returns
The path that can be write/read a file in

Implemented in FileUtilsWinRT.

◆ isPopupNotify()

virtual bool isPopupNotify ( ) const
virtual

Checks whether to pop up a message box when failed to load an image.

Returns
True if pop up a message box when failed to load an image, false if not.

◆ getValueMapFromFile()

virtual ValueMap getValueMapFromFile ( std::string_view filename) const
virtual

Converts the contents of a file to a ValueMap.

Parameters
filenameThe filename of the file to gets content.
Returns
ValueMap of the file contents.
Note
This method is used internally.

◆ getValueMapFromData()

virtual ValueMap getValueMapFromData ( const char * filedata,
int filesize ) const
virtual

Converts the contents of a file to a ValueMap.

This method is used internally.

◆ writeToFile()

virtual bool writeToFile ( const ValueMap & dict,
std::string_view fullPath ) const
virtual

write a ValueMap into a plist file

Parameters
dictthe ValueMap want to save
fullPathThe full path to the file you want to save a string
Returns
bool

◆ writeStringToFile()

virtual bool writeStringToFile ( std::string_view dataStr,
std::string_view fullPath ) const
virtual

write a string into a file

Parameters
dataStrthe string want to save
fullPathThe full path to the file you want to save a string
Returns
bool True if write success

◆ writeDataToFile()

virtual bool writeDataToFile ( const Data & data,
std::string_view fullPath ) const
virtual

write Data into a file

Parameters
datathe data want to save
fullPathThe full path to the file you want to save a string
Returns
bool

◆ writeXmlDocToFile()

bool writeXmlDocToFile ( const pugi::xml_document & xmlDoc,
std::string_view fullPath )
static

save xml document to file

Parameters
xmlDocthe xmlDoc want to save
fullPathThe full path to the file you want to save a string
Returns
bool
Since
axmol-3.0

◆ writeValueMapToFile()

virtual bool writeValueMapToFile ( const ValueMap & dict,
std::string_view fullPath ) const
virtual

write ValueMap into a plist file

Parameters
dictthe ValueMap want to save
fullPathThe full path to the file you want to save a string
Returns
bool

◆ writeValueVectorToFile()

virtual bool writeValueVectorToFile ( const ValueVector & vecData,
std::string_view fullPath ) const
virtual

write ValueVector into a plist file

Parameters
vecDatathe ValueVector want to save
fullPathThe full path to the file you want to save a string
Returns
bool

◆ isFileExist()

virtual bool isFileExist ( std::string_view filename) const
virtual

Checks whether a file exists.

Note
If a relative path was passed in, it will be inserted a default root path at the beginning.
Parameters
filenameThe path of the file, it could be a relative or absolute path.
Returns
True if the file exists, false if not.

◆ getPathExtension()

std::string getPathExtension ( std::string_view filePath)
static

Gets filename extension is a suffix (separated from the base filename by a dot) in lower case.

Examples of filename extensions are .png, .jpeg, .exe, .dmg and .txt.

Parameters
filePathThe path of the file, it could be a relative or absolute path.
Returns
suffix for filename in lower case or empty if a dot not found.

◆ isAbsolutePath()

virtual bool isAbsolutePath ( std::string_view path) const
virtual

Checks whether the path is an absolute path.

Note
On Android, if the parameter passed in is relative to "assets/", this method will treat it as an absolute path. Also on Blackberry, path starts with "app/native/Resources/" is treated as an absolute path.
Parameters
pathThe path that needs to be checked.
Returns
True if it's an absolute path, false if not.

Reimplemented in FileUtilsWinRT.

◆ isDirectoryExist()

virtual bool isDirectoryExist ( std::string_view dirPath) const
virtual

Checks whether the path is a directory.

Parameters
dirPathThe path of the directory, it could be a relative or an absolute path.
Returns
True if the directory exists, false if not.

◆ createDirectories()

virtual bool createDirectories ( std::string_view dirPath) const
virtual

Creates a directory.

Parameters
dirPathThe path of the directory, it must be an absolute path.
Returns
True if the directory have been created successfully, false if not.

◆ removeDirectory()

virtual bool removeDirectory ( std::string_view dirPath) const
virtual

Removes a directory.

Parameters
dirPathThe full path of the directory, it must be an absolute path.
Returns
True if the directory have been removed successfully, false if not.

◆ removeFile()

virtual bool removeFile ( std::string_view filepath) const
virtual

Removes a file.

Parameters
filepathThe full path of the file, it must be an absolute path.
Returns
True if the file have been removed successfully, false if not.

◆ renameFile() [1/2]

virtual bool renameFile ( std::string_view path,
std::string_view oldname,
std::string_view name ) const
virtual

Renames a file under the given directory.

Parameters
pathThe parent directory path of the file, it must be an absolute path.
oldnameThe current name of the file.
nameThe new name of the file.
Returns
True if the file have been renamed successfully, false if not.

◆ renameFile() [2/2]

virtual bool renameFile ( std::string_view oldfullpath,
std::string_view newfullpath ) const
virtual

Renames a file under the given directory.

Parameters
oldfullpathThe current fullpath of the file. Includes path and name.
newfullpathThe new fullpath of the file. Includes path and name.
Returns
True if the file have been renamed successfully, false if not.

◆ getFileSize()

virtual int64_t getFileSize ( std::string_view filepath) const
virtual

Retrieve the file size.

Note
If a relative path was passed in, it will be inserted a default root path at the beginning.
Parameters
filepathThe path of the file, it could be a relative or absolute path.
Returns
The file size.

Reimplemented in FileUtilsWinRT.

◆ listFiles()

virtual std::vector< std::string > listFiles ( std::string_view dirPath) const
virtual

List all files in a directory.

Parameters
dirPathThe path of the directory, it could be a relative or an absolute path.
Returns
File paths in a string vector

◆ listFilesRecursively()

virtual void listFilesRecursively ( std::string_view dirPath,
std::vector< std::string > * files ) const
virtual

List all files recursively in a directory.

Parameters
dirPathThe path of the directory, it could be a relative or an absolute path.
Returns
File paths in a string vector

◆ isFileExistInternal()

virtual bool isFileExistInternal ( std::string_view filename) const
pure virtual

Checks whether a file exists without considering search paths and resolution orders.

Parameters
filenameThe file (with absolute path) to look up for
Returns
Returns true if the file found at the given absolute path, otherwise returns false

◆ isDirectoryExistInternal()

virtual bool isDirectoryExistInternal ( std::string_view dirPath) const
virtual

Checks whether a directory exists without considering search paths and resolution orders.

Parameters
dirPathThe directory (with absolute path) to look up for
Returns
Returns true if the directory found at the given absolute path, otherwise returns false

◆ openFileStream()

virtual std::unique_ptr< IFileStream > openFileStream ( std::string_view filePath,
IFileStream::Mode mode ) const
virtual

Open a FileStream based on the implementation provided in openFileStream or its overrides.

Parameters
filePathThe path to the file
modeThe mode to open the file in, being READ | WRITE | APPEND
Returns
Returns a pointer to the file stream

◆ copyFile()

bool copyFile ( std::string_view sourcePath,
std::string_view destinationPath,
int64_t bufferSize = -1 )

Copy a file from source to destination.

This function copies the contents of a file located at sourcePath to a new file at destinationPath.

Parameters
sourcePathPath to the source file (must exist and be readable).
destinationPathPath to the destination file (must be writable).
bufferSizeSize of the buffer used for copying.
  • If set to -1, no buffer is used (direct copy), which is suitable for small files.
  • If set to a positive value, a buffer of that size (in bytes) is allocated to improve performance for larger files.
Note
Destination path handling rules:
  • Absolute path: must point to a writable location on disk. If a file already exists at that location, it may be overwritten.
  • Relative path: will be resolved against the engine's writablePath.
  • In both cases, the caller must ensure that the parent directory of the destination path exists.

The documentation for this class was generated from the following file:
  • FileUtils.h