# File

Interface for basic file and directory operations.

## File information

File | common/interface/file.h
Classes | FileSystem IFileWrite IFileRead IDirectory IDirectoryEntry IElfBinary IElfUserData
Datatypes | IFileRead::ORIGIN elf_architecture_t IElfBinary::UserDataID
Examples | class FileSystem FileSystem::OpenWriteFile FileSystem::OpenReadFile FileSystem::OpenDirectory FileSystem::OpenElfBinary FileSystem::WriteWholeFile FileSystem::WriteBinaryFile FileSystem::ScanFile FileSystem::Rename FileSystem::CreateDirectory FileSystem::ChangeMode FileSystem::GetFileSystemTotalSize class IFileWrite class IDirectory

# Classes

## FileSystem

    class FileSystem {
    public:
        static class IFileWrite * OpenWriteFile(const char * fileName, bool append, class IInstanceLog * log);
        static class IFileRead * OpenReadFile(const char * fileName, class IInstanceLog * log);
        static class IDirectory * OpenDirectory(const char * directoryName, class IInstanceLog * log);
        static class IElfBinary * OpenElfBinary(const char * bin, class IInstanceLog * log);
        static bool ReadWholeFile(const char * filename, char * readBuffer, size_t size, class IInstanceLog * log);
        static bool ReadBinaryFile(const char * filename, byte * readBuffer, size_t size, class IInstanceLog * log);
        static bool WriteWholeFile(const char * filename, const char * writeBuffer, size_t size, class IInstanceLog * log);
        static bool WriteBinaryFile(const char * filename, const byte * writeBuffer, size_t size, class IInstanceLog * log);
        static bool ScanFile(class IInstanceLog * log, const char * filename, const char * format, ...);
        static bool FileExists(const char * filename, class IInstanceLog * log);
        static time_t GetLastWriteTime(const char * filename, class IInstanceLog * log);
        static bool SetLastWriteTime(const char * filename, long64 writeTimeMs, class IInstanceLog * log);
        static off_t GetFileSize(const char * filename, class IInstanceLog * log);
        static off_t GetFileBlockSize(const char * filename, class IInstanceLog * log);
        static bool Rename(const char * oldName, const char * newName, class IInstanceLog * log);
        static bool RemoveFile(const char * filename, class IInstanceLog * log);
        static bool CreateDirectory(const char * absolutePath, int mode, class IInstanceLog * log);
        static bool RemoveDirectory(const char * directoryPath, class IInstanceLog * log);
        static bool ChangeOwner(const char * path, const char * newOwner, const char * newGroup, class IInstanceLog * log);
        static bool ChangeMode(const char * path, int mode, class IInstanceLog * log);
        static ulong64 GetFileSystemTotalSize(const char * path, class IInstanceLog * log);
        static ulong64 GetFileSystemUsedSpace(const char * path, class IInstanceLog * log);
        static bool CheckSystemUser(const char * user, const char * group, class IInstanceLog * log);
        static char * GetFileSystemUser(const char * filepath, class IInstanceLog * log);
    };

### Overview

The basic class to perform read/write and create/rename/remove operations on linux files and directories. It also offers some functions to obtain information about file/block sizes, last write time of files and system users, and some other functions to maniplulate file owners or modes.

### Logging

To enable logging for File interface, the flag LOG_FILE must be set in the Manager App diagnostic settings.

### Public functions

OpenWriteFile (static function)

  The main function to use to open a file for write operation. An empty file is created and opened for writinf if append is false; otherwise the file is opened for the writing at the end of the file. If the file is opened successfully, an object of class IFileWrite is returned. In case of error, a null pointer is returned.

  #### Parameters

  const char * fileName | The absolute full path of the file
  bool append | Specifies whether a file is to be opened for append oor write operation
  class IInstanceLog * log | The IInstanceLog instance used for loging purposes.

  #### Return value

  The IFileWrite instance created. It must be freed by the C++ operator delete, if no longer needed.

  #### Code Example

      class IFileWrite * file = FileSystem::OpenWriteFile("/path/file.txt", false, log_instance);
      if(file) {
      ....
        write operation
      ...
      delete file;
      }

OpenReadFile (static function)

  The main function to open an exisitng file for a read operation. On success, an object of the class IFileRead is returned which can be used to read the content of the file; otherwise a null pointer is returned.

  #### Parameters

  const char * fileName | The absolute full path of the file
  class IInstanceLog * log | The IInstanceLog instance used for loging purposes.

  #### Return value

  The IFileRead instance created. It must be freed by the C++ operator delete, if no longer be used.

  #### Code Example

      class IFileRead * file = FileSystem::OpenReadFile("/path/file.txt", log_instance);
      if(file) {
      ....
        read operation
      ...
      delete file;
      }

OpenDirectory (static function)

  The main function to use to open a directory corresponding to directoryName. An object of class IDirectory is returned on success and a null pointer on failure.

  #### Parameters

  const char * directoryName | The absolute full name of the directory
  class IInstanceLog * log | The IInstanceLog instance used for loging purposes.

  #### Return value

  The created IDirectory instance. It must be freed by the C++ operator delete, if no longer be used.

  #### Code Example

      class IDirectory * dir = FileSystem::OpenDirectory("/dir/", log_instance);
      if(dir) {
      ....
        perform action
      ...
      delete dir;
      }

OpenElfBinary (static function)

  The function is used to open a binary file bin. An object of class IElfBinary is returned on success and a null pointer on failure. This object can be used to get some information about an ELF (Executable and Linkable Format) binary.

  #### Parameters

  const char * bin | The absolute full name of the binary
  class IInstanceLog * log | The IInstanceLog instance used for loging purposes.

  #### Return value

  The created IElfBinary instance. It must be freed by the C++ operator delete, if no longer be used.

  #### Code Example

      class IElfBinary * bin = FileSystem::OpenElfBinary(binary, log_instance);
      if(bin) {
      ....
        perform action
      ...
      delete bin;
      }

ReadWholeFile (static function)

  Opens and reads the whole file into a buffer with a defined size. The file is closed afterwards. The file must contain strings.

  #### Parameters

  const char * filename | The absolute path of the file
  char * readBuffer | The buffer in which the file is read to
  size_t size | The size of the read buffer which must be big enough
  class IInstanceLog * log | The IInstanceLog instance used for loging purposes.

  #### Return value

  If the read is successfull true is returned; otherwise false.

ReadBinaryFile (static function)

  Opens and reads the whole file into a buffer with a defined size. The file is closed afterwards.

  #### Parameters

  const char * filename | The absolute path of the file
  byte * readBuffer | The buffer in which the file is read to
  size_t size | The size of the read buffer which must be big enough
  class IInstanceLog * log | The IInstanceLog instance used for loging purposes.

  #### Return value

  If the read is successfull true is returned; otherwise false.

WriteWholeFile (static function)

  Opens a file with an absolute path and writes the whole content of the write buffer into the file. The file is closed afterwards.

  #### Note

  This function just writes a NULL terminated string and the size is ignored! Thus this function is deprecated and you should use WriteBinaryFile instead!

  #### Parameters

  const char * filename | The absolute path of the file
  const char * writeBuffer | The buffer to be written to the file. Must be a NULL terminated string.
  size_t size | The size of the write buffer.
  class IInstanceLog * log | The IInstanceLog instance used for loging purposes.

  #### Return value

  If the write is successfull true is returned; otherwise false.

  #### Code Example

      char * buffer = malloc(BIG_ENOUGH_SIZE);
      FileSystem::WriteWholeFile("/path/important_file.txt", buffer, strlen(buffer), log_instance);
      free(buffer);

WriteBinaryFile (static function)

  Opens a file with an absolute path and writes the whole content of the write buffer into the file. The file is closed afterwards.

  #### Parameters

  const char * filename | The absolute path of the file
  cosnt byte * writeBuffer | The buffer to be written to the file
  size_t size | The size of the write buffer.
  class IInstanceLog * log | The IInstanceLog instance used for loging purposes.

  #### Return value

  If the write is successfull true is returned; otherwise false.

  #### Code Example

      byte buffer[BIG_ENOUGH_SIZE];
      FileSystem::WriteBinaryFile("/path/important_file.txt", buffer, sizeof(buffer), log_instance);

ScanFile (static function)

  Scans a file given as an absolute path, based on a set of characters specified in a format string.

  #### Parameters

  class IInstanceLog * log | The IInstanceLog instance used for loging purposes.
  const char * filename | The absolute path of the file
  const char * format | A string containing a set of characters that specifies how characters are extracted from the file (C string following the same specifications as in the C function scanf.)

  #### Return value

  If scanning the file is successfull, the file is closed and true is returned; otherwise false.

  #### Code Example

      long long unsigned time;
      int id;
      char s_string[128];
      FileSystem::ScanFile(log_instance, "/path/file_to_scan", "%*32[^:]:%llu %*s %d %s", &time, &id, s_string);

FileExists (static function)

  Checks if a file exists.

  #### Parameters

  const char * filename | The absolute path of the file
  class IInstanceLog * log | The IInstanceLog instance used for loging purposes.

  #### Return value

  If a file exists true is returned; otherwise false.

GetLastWriteTime (static function)

  Returns the time of the last write operation performed on a file specified by an absolute path.

  #### Parameters

  const char * filename | The absolute path of the file
  class IInstanceLog * log | The IInstanceLog instance used for loging purposes.

  #### Return value

  On success the time in seconds is retured; otherwise -1.

SetLastWriteTime (static function)

  Sets the modified and last access time of a file specified by an absolute path.

  #### Parameters

  const char * filename | The absolute path of the file
  long64 writeTimeMs | UTC timestamp in milliseconds
  class IInstanceLog * log | The IInstanceLog instance used for loging purposes.

  #### Return value

  On success true, otherwise false.

GetFileSize (static function)

  Returns the current size of the file.

  #### Parameters

  const char * filename | The absolute path of the file
  class IInstanceLog * log | The IInstanceLog instance used for loging purposes.

  #### Return value

  On success the size of the file is retured; otherwise -1.

GetFileBlockSize (static function)

  Returns the current block size of the file.

  #### Parameters

  const char * filename | The absolute path of the file
  class IInstanceLog * log | The IInstanceLog instance used for loging purposes.

  #### Return value

  On success the block size of the file is retured; otherwise -1.

Rename (static function)

  Renames a file.

  #### Parameters

  const char * oldName | The current name of the file (absolute path)
  const char * newName | The new name of the file (absolute path)
  class IInstanceLog * log | The IInstanceLog instance used for loging purposes.

  #### Return value

  On success true is retured; otherwise false.

  #### Code Example

      if (FileSystem::FileExists("/path/myPbx.txt", log_instance)) {
          FileSystem::Rename("/path/myPbx.txt", "/path/myApps.txt", log_instance);
      }

RemoveFile (static function)

  Removes a file.

  #### Parameters

  const char * filename | The absolute path of the file to be removed
  class IInstanceLog * log | The IInstanceLog instance used for loging purposes.

  #### Return value

  On success true is retured; otherwise false.

CreateDirectory (static function)

  Creates a directory.

  #### Parameters

  const char * absolutePath | The absolute path of the directory to be created
  int mode | The mode to set the file permission bits
  class IInstanceLog * log | The IInstanceLog instance used for loging purposes.

  #### Return value

  On success true is retured; otherwise false.

  #### Code Example

      //mode 0755 defined as rwxr-xr-x
      FileSystem::CreateDirectory("/home/new", 0755, log)

RemoveDirectory (static function)

  Removes a directory. If the directory is not empty, all included directories and files are deleted as well.

  #### Parameters

  const char * directoryPath | The absolute path of the directory to be removed
  class IInstanceLog * log | The IInstanceLog instance used for loging purposes.

  #### Return value

  On success true is retured; otherwise false.

ChangeOwner (static function)

  Changes the owner and group of the directory specified by an absolute path.

  #### Parameters

  const char * path | The absolute path of the directory
  const char * newOwner | The new owner of the directory
  const char * newGroup | The new group of the directory
  class IInstanceLog * log | The IInstanceLog instance used for loging purposes.

  #### Return value

  On success true is retured; otherwise false.

ChangeMode (static function)

  Changes the mode of a file.

  #### Parameters

  const char * path | The absolute path of the directory to be removed
  int mode | The new mode of the file
  class IInstanceLog * log | The IInstanceLog instance used for loging purposes.

  #### Return value

  On success true is retured; otherwise false.

  #### Code Example

      FileSystem::ChangeMode("/directory", 0744, log);

GetFileSystemTotalSize (static function)

  Returns the total size of the file system in bytes.

  #### Parameters

  const char * path | The absolute path of the directory to be removed
  class IInstanceLog * log | The IInstanceLog instance used for loging purposes.

  #### Return value

  On success the size is returned in bytes; otherwise -1.

  #### Code Example

      ulong64 totalSize = FileSystem::GetFileSystemTotalSize("/mnt/sda1", log);

GetFileSystemUsedSpace (static function)

  Returns the total used space of the file system in bytes.

  #### Parameters

  const char * path | The absolute path of the directory to be removed
  class IInstanceLog * log | The IInstanceLog instance used for loging purposes.

  #### Return value

  On success the size is returned in bytes; otherwise -1.

CheckSystemUser (static function)

  Checks if a system user and group exist.

  #### Parameters

  const char * user | The system user
  const char * group | The system group
  class IInstanceLog * log | The IInstanceLog instance used for loging purposes.

  #### Return value

  If the user and group are available to use, true is returned; otherwise false.

GetFileSystemUser (static function)

  Returns the system user of a file.

  #### Parameters

  const char * filepath | The absolute path of the file
  class IInstanceLog * log | The IInstanceLog instance used for loging purposes.

  #### Return value

  On success, returns the system user; otherwise 0.

## IFileWrite

    class IFileWrite {
    public:
        ~IFileWrite() {};
        bool IsOpen();
        bool Write(const void * buffer, size_t len);
        void Flush();
        bool Close();
    };

### Overview

An instance of this class is created after a call to FileSystem::OpenWriteFile

### Logging

To enable logging for File interface, the flag LOG_FILE must be set in the managers diagnostic settings.

### Public functions

IsOpen

  Checks if the file is opened.

  #### Return value

  Returns true if the file is opened successfully; otherwise false.

Write

  Writes the buffer with a size len into the file.

  #### Parameters

  const void * buffer | The buffer to be written
  size_t len | The length of the buffer

  #### Return value

  Returns true if the write operation was successful; otherwise false.

Flush (static function)

  Flushes the stream opened for writing any unwritten data

Close

  Close the file after writing is finished. After the write operation is completed, a call to Close() should be performed explicitly.

  #### Return value

  Returns true if the the file was closed successfully; otherwise false.

### Code Example

    bool append = false;
    class IFileWrite * file = FileSystem::OpenWriteFile("file.txt", append, log);
    file->Write(buffer, strlen(buffer));
    file->Close();
    delete file;

## IFileRead

    class IFileRead {
    public:
        virtual ~IFileRead() {};
        bool IsOpen();
        size_t Read(void * buffer, size_t len);
        bool Close();
        bool Seek(size_t offset, Origin origin = Origin::CURRENT);
    };

### Overview

An instance of this class is created after a call to FileSystem::OpenReadFile

### Logging

To enable logging for File interface, the flag LOG_FILE must be set in the managers diagnostic settings.

### Public functions

IsOpen

  Checks if the file is opened.

  #### Return value

  Returns true if the file is opened successfully; otherwise false.

Read

  Reads the file into the buffer.

  #### Parameters

  void * buffer | The buffer to read the file into
  size_t len | The length of the buffer

  #### Return value

  Returns the count of the written bytes in the buffer.

Close

  Close the file after writing is finished. After the last read operation is completed, a call to Close() should be performed explicitly.

  #### Return value

  Returns true if the the file was closed successfully; otherwise false.

Seek

  Changes the read position inside of the file.

  #### Parameters

  size_t offset | The position to set starting from.
  IFileRead::Origin origin | (Default IFileRead::Origin::CURRENT The position to start from.

  #### Return value

  Returns true if the operation was successful; otherwise false.

## IDirectory

    class IDirectory {
    public:
        ~IDirectory() {};
        bool IsOpen() const;
        class IDirectoryEntry * ReadNext();
        bool Close();
    };

### Overview

An instance of this class is created after a call to FileSystem::OpenDirectory. The directory is opened and the first entry is ready to be read.

### Logging

To enable logging for File interface, the flag LOG_FILE must be set in the managers diagnostic settings.

### Public functions

IsOpen

  Checks if the directory is opened.

  #### Return value

  Returns true if the directory is opened successfully; otherwise false.

ReadNext

  Starts reading the first entry of the directory. This function iterates through the whole directory till end of the directory is reached or if an error occurs.

  #### Return value

  An instance of class DirectoryEntry is returned specifying whether the entry is a regular file or a directory. NULL is returned on error or if the end of directory is reached.

Close

  Closes the associated directory. A call to Close() should be done explicitly after reading is done.

  #### Return value

  Returns true if the the directory was closed successfully; otherwise false.

### Code Example

    class IDirectory * dir = FileSystem::OpenDirectory("/directory", log);
    class IDirectoryEntry * entry;
    while ((entry = dir->ReadNext())) {
        ......
        ......
        delete entry;
    }
    dir->Close();
    delete dir;

## IDirectoryEntry

    class IDirectoryEntry {
    public:
        ~IDirectoryEntry() {};
        const char * GetName() const ;
        bool IsFile() const ;
    };

### Overview

An instance of this class is created after every ReadNext() function call. After this object is no longer needed, it should be deleted.

### Logging

To enable logging for File interface, the flag LOG_FILE must be set in the managers diagnostic settings.

### Public functions

GetName

  Reads the name of the directory entry.

  #### Return value

  Returns the name read.

IsFile

  Checks if the directory entry is a regular file.

  #### Return value

  Returns true if the read directory entry is a regular file or false if the entry is a directory.

## IElfBinary

    class IElfBinary {
    public:
        ~IElfBinary() {};
        bool IsOpen() ;
        bool IsElfBinary() ;
        bool IsExecutable() ;
        elf_architecture_t GetArchitecture();
        bool Close();
        class IElfUserData * GetUserData(UserDataID userDataID);
        UserDataID MakeUserID(word userDefinedValue);
        size_t GetSharedLibrariesCount();
        const char * GetSharedLibrary(size_t index);
    };

### Overview

An instance of this class is created after a call to FileSystem::OpenElfBinary(). After this object is no longer needed, it should be deleted.

### Logging

To enable logging for File interface, the flag LOG_FILE must be set in the managers diagnostic settings.

### Public functions

IsOpen

  Check if the binary file is opened.

  #### Return value

  Returns true if the file is successfully opened.

IsElfBinary

  Checks whether the file is a valid ELF binary. The header of the binary is read the magic number is checked.

  #### Return value

  Returns true if the binary is a valid ELF binary.

IsExecutable

  Checks whether the file is an executible ELF binary.

  #### Return value

  Returns true if the binary is executable; otherwise false.

GetArchitecture

  Returns the architecture of the ELF binary. The types checked are ARM, ARM64 and X86_64 only.

  #### Return value

  Returns the architecture in the enum elf_architecture_t.

Close

  Closes the binary file.

  #### Return value

  Returns true if the the directory was closed successfully; otherwise false.

GetUserData

  Searches in the ELF binary for a user data block with the given ID and returns the object to access it.

  #### Parameters

  void * buffer | The buffer to store the data to. The size of the buffer must be at least bufferLen bytes.
  size_t bufferLen | The size of the given buffer.

  #### Return value

  The IElfUserData object to access the user data or nullptr, if the requested user data could not be found inside the binary.

  #### Remarks

  The object returned by the function must be deleted by the app if no longer used.

MakeUserID

  Creates an ID to a user data block to be access by GetUserData(). Every ID below 0x7FFF is reserved for innovaphone internal usage. Everything from 0x7FFF (which is IElfBinary::UserDataID::USER) on can be used for you own, user defined IDs. It is recommended to define your own zero based IDs and map them by using MakeUserID.

  #### Parameters

  word userDefinedValue | The value of your user ID (the IElfBinary::UserDataID::USER value not included!).

  #### Return value

  The ID for your user data added to the ELF binary as a UserDataID enum type.

GetSharedLibrariesCount

  Returns the count of shared libraries against which this binary is linked.

  #### Return value

  size_t

GetSharedLibrary

  Gets the relative name of the shared library at the given index.

  #### Parameters

  size_t index | The index of the shared library name (must be within GetSharedLibrariesCount()).

  #### Return value

  Name of the shared library. The name mustn't be freed!

## IElfUserData

    class IElfUserData {
    public:
        IElfUserData() {};
        virtual ~IElfUserData() {};

         IElfBinary::UserDataID ID();
         size_t DataSize();
         size_t Read(void * buffer, size_t bufferLen);
         bool Seek(size_t offset, IFileRead::Origin origin = IFileRead::Origin::CURRENT);
    };

### Overview

This interface allows the access to user data added to a binary. An instance of this interface will be created by the call to IElfBinary::GetUserData() (see IElfBinary for details).

### Logging

IElfUserData uses an IFileRead instance. So the same logging rules will apply.

### Public functions

UserDataID

  #### Return value

  Returns true if the the directory was closed successfully; otherwise false.

DataSize

  #### Return value

  Returns the data size of the user data.

Read

  Read the user data to the given buffer starting from the current position in the file (which can be set by calling Seek). The amount of data read will be either the given number of bytes or the number of bytes available from the current position, if it is less then the requested byte number.

  #### Parameters

  void * buffer | The buffer to store the data to. The size of the buffer must be at least bufferLen bytes.
  size_t bufferLen | The size of the given buffer.

  #### Return value

  The actuall number of bytes read. Can be less than the value given to bufferLen.

Seek

  Set the position of the file pointer inside the area of the user data. That means, IFileRead::Origin::BEGIN will not be the begin of the ELF binary itself, it will be the begin of the user data block. The same applies to the meaning of IFileRead::Origin::END.

  #### Parameters

  size_t offset | The number of bytes to move the current fileposition inside the user data block.
  IFileRead::Origin origin | (Default IFileRead::Origin::CURRENT) The position to start from.

  #### Return value

  True, if the operation was successfull, else false.

# Datatypes

## IFileRead::ORIGIN

    class IFileRead {
    public:
        enum Origin {
            START,
            CURRENT,
            END
        };
    };

### Overview

This enum defines the position from where the offset on seek operations should be applied.

### Values

START | The seek offset will be applied from the start of the file.
CURRENT | The seek offset will be applied from the current position of the file pointer.
END | The seek offset will be applied from the end of the file.

## elf_architecture_t

    typedef enum {
        ELF_UNKOWN,
        ELF_ARM,
        ELF_X86_64,
        ELF_ARM64
    } elf_architecture_t;

### Overview

This enum defines the architecture of the elf binary had been compiled for. While there are a lot of different architectures are available, this enum only holds the one supported by the App Platform.

### Values

ELF_UNKOWN | The file is a valid ELF binary but the architecture the binary had been compiled for is unkown for the app platform.
ELF_ARM | The binary had been compiled for the 32bit ARM architecture.
ELF_X86_64 | The binary had been compiled for the 64bit x86 architecture.
ELF_ARM64 | The binary had been compiled for the 64bit ARM architecture.

## IElfBinary::UserDataID

    class IElfBinary {
    public:
        enum UserDataID {
            NONE        = 0x0000,
            HTTP_FILES  = 0x0001,
            USER        = 0x7FFF
        };
    };

### Overview

This enum is used for the user data, that can be added to an ELF binary. See IElfUserData for more information.

### Values

NONE | A dummy variable used for initialization purposes only.
HTTP_FILES | HTTP files bound to the binary. Handled internally by the JavaScript runtime for App Platform services written in JavaScript.
USER | User data not defined by innovaphone. Can be used for your own user data to be added to the binary. It is recommended, to define an own ID based on this value.