OpenMS
File Class Reference

Basic file handling operations. More...

#include <OpenMS/SYSTEM/File.h>

Collaboration diagram for File:
[legend]

Classes

class  TempDir
 Class representing a temporary directory. More...
 
class  TemporaryFiles_
 Internal helper class, which holds temporary filenames and deletes these files at program exit. More...
 

Public Types

enum class  CopyOptions { OVERWRITE , SKIP , CANCEL }
 Copy directory recursively. More...
 
enum class  MatchingFileListsStatus { MATCH = 0 , ORDER_MISMATCH = 1 , SET_MISMATCH = 2 }
 

Static Public Member Functions

static String getExecutablePath ()
 
static bool exists (const String &file)
 Method used to test if a file exists. More...
 
static bool empty (const String &file)
 Return true if the file does not exist or the file is empty. More...
 
static bool executable (const String &file)
 Method used to test if a file is executable. More...
 
static UInt64 fileSize (const String &file)
 The filesize in bytes (or -1 on error, e.g. if the file does not exist) More...
 
static bool rename (const String &from, const String &to, bool overwrite_existing=true, bool verbose=true)
 Rename a file. More...
 
static bool copyDirRecursively (const QString &from_dir, const QString &to_dir, File::CopyOptions option=CopyOptions::OVERWRITE)
 
static bool copy (const String &from, const String &to)
 Copy a file (if it exists). Returns true if successful. More...
 
static bool remove (const String &file)
 Removes a file (if it exists). More...
 
static bool removeDirRecursively (const String &dir_name)
 Removes the subdirectories of the specified directory (absolute path). Returns true if successful. More...
 
static bool removeDir (const QString &dir_name)
 Removes the directory and all subdirectories (absolute path). More...
 
static bool makeDir (const String &dir_name)
 
static String absolutePath (const String &file)
 Replaces the relative path in the argument with the absolute path. More...
 
static String basename (const String &file)
 
static String path (const String &file)
 
static bool readable (const String &file)
 Return true if the file exists and is readable. More...
 
static bool writable (const String &file)
 Return true if the file is writable. More...
 
static bool isDirectory (const String &path)
 Return true if the given path specifies a directory. More...
 
static String find (const String &filename, StringList directories=StringList())
 Looks up the location of the file filename. More...
 
static bool fileList (const String &dir, const String &file_pattern, StringList &output, bool full_path=false)
 Retrieves a list of files matching file_pattern in directory dir (returns filenames without paths unless full_path is true) More...
 
static String findDoc (const String &filename)
 Resolves a partial file name to a documentation file in the doc-folder. More...
 
static String getUniqueName (bool include_hostname=true)
 Returns a string, consisting of date, time, hostname, process id, and a incrementing number. This can be used for temporary files. More...
 
static String getOpenMSDataPath ()
 Returns the OpenMS data path (environment variable overwrites the default installation path) More...
 
static String getOpenMSHomePath ()
 Returns the OpenMS home path (environment variable overwrites the default home path) More...
 
static String getTempDirectory ()
 
static String getUserDirectory ()
 
static Param getSystemParameters ()
 
static String findDatabase (const String &db_name)
 
static StringList getPathLocations (const String &path=std::getenv("PATH"))
 Extract list of directories from a concatenated string (usually $PATH). More...
 
static bool findExecutable (OpenMS::String &exe_filename)
 Searches for an executable with the given name (similar to where (Windows) or which (Linux/MacOS) More...
 
static String findSiblingTOPPExecutable (const String &toolName)
 Searches for an executable with the given name. More...
 
static String getTemporaryFile (const String &alternative_file="")
 Obtain a temporary filename, ensuring automatic deletion upon exit. More...
 
static MatchingFileListsStatus validateMatchingFileNames (const StringList &sl1, const StringList &sl2, bool basename=true, bool ignore_extension=true)
 Helper function to test if filenames provided in two StringLists match. More...
 
static void download (const std::string &url, const std::string &download_folder)
 Download file from given URL into a download folder. Returns when done. More...
 

Static Private Member Functions

static Param getSystemParameterDefaults_ ()
 get defaults for the system's Temp-path, user home directory etc. More...
 
static bool isOpenMSDataPath_ (const String &path)
 Check if the given path is a valid OPENMS_DATA_PATH. More...
 

Static Private Attributes

static TemporaryFiles_ temporary_files_
 private list of temporary filenames, which are deleted upon program exit More...
 

Friends

class TOPPBase
 

Detailed Description

Basic file handling operations.

Member Enumeration Documentation

◆ CopyOptions

enum CopyOptions
strong

Copy directory recursively.

Copies a source directory to a new target directory (recursive). If the target directory already exists, files will be added. If files from the source already exist in the target, option allows for the following behaviour:

OVERWRITE: Overwrite the file in the target directory if it already exists. SKIP: Skip the file in the target directory if it already exists. CANCEL: Cancel the copy process if file already exists in target directory - return false.

Parameters
from_dirSource directory
to_dirTarget directory
optionSpecify the copy option (OVERWRITE, SKIP, CANCEL)
Returns
True on success
Enumerator
OVERWRITE 
SKIP 
CANCEL 

◆ MatchingFileListsStatus

Enumerator
MATCH 
ORDER_MISMATCH 
SET_MISMATCH 

Member Function Documentation

◆ absolutePath()

static String absolutePath ( const String file)
static

Replaces the relative path in the argument with the absolute path.

Referenced by TOPPViewBase::addDataFile().

◆ basename()

static String basename ( const String file)
static

Returns the basename of the file (without the path). No checking is done on the filesystem, i.e. '/path/some_entity' will return 'some_entity', irrespective of 'some_entity' is a file or a directory. However, '/path/some_entity/' will return ''.

Referenced by TOPPViewBase::addDataFile(), TOPPASBase::addTOPPASFile(), DTAFile::load(), NucleicAcidSearchEngine::main_(), TOPPASBase::refreshParameters(), AccurateMassSearchEngine::resolveAutoMode_(), TOPPASBase::saveCurrentPipelineAs(), TOPPASBase::savePipeline(), TOPPASBase::savePipelineAs(), and INIFileEditorWindow::updateWindowTitle().

◆ copy()

static bool copy ( const String from,
const String to 
)
static

Copy a file (if it exists). Returns true if successful.

◆ copyDirRecursively()

static bool copyDirRecursively ( const QString &  from_dir,
const QString &  to_dir,
File::CopyOptions  option = CopyOptions::OVERWRITE 
)
static

◆ download()

static void download ( const std::string &  url,
const std::string &  download_folder 
)
static

Download file from given URL into a download folder. Returns when done.

If a file with same filename already exists, continues download and appends '.#number' to basename.

Exceptions
FileNotFoundexception if download failed.

◆ empty()

static bool empty ( const String file)
static

Return true if the file does not exist or the file is empty.

◆ executable()

static bool executable ( const String file)
static

Method used to test if a file is executable.

◆ exists()

static bool exists ( const String file)
static

◆ fileList()

static bool fileList ( const String dir,
const String file_pattern,
StringList output,
bool  full_path = false 
)
static

Retrieves a list of files matching file_pattern in directory dir (returns filenames without paths unless full_path is true)

Returns
true => there are matching files

◆ fileSize()

static UInt64 fileSize ( const String file)
static

The filesize in bytes (or -1 on error, e.g. if the file does not exist)

◆ find()

static String find ( const String filename,
StringList  directories = StringList() 
)
static

Looks up the location of the file filename.

The following locations are checked in this order:

  • the directories in directories
  • the directory contained in the environment variable $OPENMS_DATA_PATH
  • the 'share/OpenMS/' directory of the OpenMS install directory
Exceptions
FileNotFoundis thrown, if the file is not found

Referenced by QApplicationTOPP::QApplicationTOPP(), and DigestionEnzymeDB< DigestionEnzymeType, InstanceType >::readEnzymesFromFile_().

◆ findDatabase()

static String findDatabase ( const String db_name)
static

uses File::find() to search for a file names db_name in the 'id_db_dir' param of the OpenMS system parameters

Exceptions
FileNotFoundis thrown, if the file is not found

◆ findDoc()

static String findDoc ( const String filename)
static

Resolves a partial file name to a documentation file in the doc-folder.

Using find() to locate the documentation file under OPENMS_DATA_PATH, OPENMS_SOURCE_PATH, OPENMS_BINARY_PATH + "/../../doc" (or a variation for MacOS packages)

Will return the filename with the full path to the local documentation. If this call fails, try the web documentation (http://www.openms.de/current_doxygen/) instead.

Parameters
filenameThe doc file name to find.
Returns
The full path to the requested file.
Exceptions
FileNotFoundis thrown, if the file is not found

◆ findExecutable()

static bool findExecutable ( OpenMS::String exe_filename)
static

Searches for an executable with the given name (similar to where (Windows) or which (Linux/MacOS)

This function can be used to find the full path+filename to an executable in the PATH environment. Only the first hit (by order in PATH) is returned. If the exe_filename has a relative or full path which points to an existing file, PATH information will not be used. The function returns true if the filename was found (exists) and false otherwise. Note: this does not require the file to have executable permission set (this is not tested) The returned content of exe_filename is only valid if true is returned.

Parameters
[in,out]exe_filenameThe executable to search for.
Returns
true if exe_filename could be resolved to a full path and it exists

◆ findSiblingTOPPExecutable()

static String findSiblingTOPPExecutable ( const String toolName)
static

Searches for an executable with the given name.

Parameters
toolNameThe executable to search for.
Exceptions
FileNotFoundis thrown, if the tool executable was not found.

Referenced by TOPPViewBase::runTOPPTool_().

◆ getExecutablePath()

static String getExecutablePath ( )
static

Retrieve path of current executable (useful to find other TOPP tools) The returned path is either just an EMPTY string if the call to system subroutines failed or the complete path including a trailing "/", to enable usage of this function as File::getExecutablePath() + "mytool"

◆ getOpenMSDataPath()

static String getOpenMSDataPath ( )
static

Returns the OpenMS data path (environment variable overwrites the default installation path)

Referenced by TOPPASBase::openExampleDialog().

◆ getOpenMSHomePath()

static String getOpenMSHomePath ( )
static

Returns the OpenMS home path (environment variable overwrites the default home path)

◆ getPathLocations()

static StringList getPathLocations ( const String path = std::getenv("PATH"))
static

Extract list of directories from a concatenated string (usually $PATH).

Depending on platform, the components are split based on ":" (Linux/Mac) or ";" (Windows). All paths use the '/' as separator and end in '/'. E.g. for 'PATH=/usr/bin:/home/unicorn' the result is {"/usr/bin/", "/home/unicorn/"} or 'PATH=c:\temp;c:\Windows' the result is {"c:/temp/", "c:/Windows/"}

Note: the environment variable is passed as input to enable proper testing (env vars are usually read-only).

◆ getSystemParameterDefaults_()

static Param getSystemParameterDefaults_ ( )
staticprivate

get defaults for the system's Temp-path, user home directory etc.

◆ getSystemParameters()

static Param getSystemParameters ( )
static

get the system's default OpenMS.ini file in the users home directory (<home>/OpenMS/OpenMS.ini) or create/repair it if required order:

  1. <OPENMS_HOME_DIR>/OpenMS/OpenMS.ini if environmental variable set
  2. user home directory <home>/OpenMS/OpenMS.ini

◆ getTempDirectory()

static String getTempDirectory ( )
static

The current OpenMS temporary data path (for temporary files). Looks up the following locations, taking the first one which is non-null:

  • environment variable OPENMS_TMPDIR
  • 'temp_dir' in the ~/OpenMS.ini file
  • System temp directory (usually defined by environment 'TMP' or 'TEMP'

Referenced by TOPPViewBase::finishTOPPToolExecution(), TOPPViewBase::showTOPPDialog_(), TOPPASBase::TOPPASBase(), and TOPPASBase::~TOPPASBase().

◆ getTemporaryFile()

static String getTemporaryFile ( const String alternative_file = "")
static

Obtain a temporary filename, ensuring automatic deletion upon exit.

The file is not actually created and only deleted at exit if it exists.

However, if 'alternative_file' is given and not empty, no temporary filename is created and 'alternative_file' is returned (and not destroyed upon exit). This is useful if you have an optional output file, which may, or may not be requested, but you need its content regardless, e.g. for intermediate plotting with R. Thus you can just call this function to get a file which can be used and gets automatically destroyed if needed.

Parameters
alternative_fileIf this string is not empty, no action is taken and it is used as return value
Returns
Full path to a temporary file

◆ getUniqueName()

static String getUniqueName ( bool  include_hostname = true)
static

Returns a string, consisting of date, time, hostname, process id, and a incrementing number. This can be used for temporary files.

Parameters
include_hostnameadd hostname into result - potentially a long string
Returns
a unique name

Referenced by TOPPViewBase::showTOPPDialog_(), and TOPPASBase::TOPPASBase().

◆ getUserDirectory()

static String getUserDirectory ( )
static

The current OpenMS user data path (for result files) Tries to set the user directory in following order:

  1. OPENMS_HOME_DIR if environmental variable set
  2. "home_dir" entry in OpenMS.ini
  3. user home directory

Referenced by TOPPViewBase::initializeDefaultParameters_(), and TOPPViewBase::loadPreferences().

◆ isDirectory()

static bool isDirectory ( const String path)
static

Return true if the given path specifies a directory.

◆ isOpenMSDataPath_()

static bool isOpenMSDataPath_ ( const String path)
staticprivate

Check if the given path is a valid OPENMS_DATA_PATH.

◆ makeDir()

static bool makeDir ( const String dir_name)
static

Creates a directory (absolute path or relative to the current working dir), even if subdirectories do not exist. Returns true if successful. If the path already exists when this function is called, it will return true.

◆ path()

static String path ( const String file)
static

Returns the path of the file (without the file name and without path separator). If just a filename is given without any path, then "." is returned. No checking is done on the filesystem, i.e. '/path/some_entity' will return '/path', irrespective of 'some_entity' is a file or a directory. However, '/path/some_entity/' will return '/path/some_entity'.

Referenced by TOPPViewBase::updateCurrentPath(), and INIFileEditorWindow::updateWindowTitle().

◆ readable()

static bool readable ( const String file)
static

Return true if the file exists and is readable.

Referenced by TOPPViewBase::finishTOPPToolExecution(), MS2File::load(), and INIFileEditorWindow::openFile().

◆ remove()

static bool remove ( const String file)
static

Removes a file (if it exists).

Returns
Returns true if the file was successfully deleted (or if it did not exist).

Referenced by TOPPViewBase::finishTOPPToolExecution(), and TOPPViewBase::runTOPPTool_().

◆ removeDir()

static bool removeDir ( const QString &  dir_name)
static

Removes the directory and all subdirectories (absolute path).

◆ removeDirRecursively()

static bool removeDirRecursively ( const String dir_name)
static

Removes the subdirectories of the specified directory (absolute path). Returns true if successful.

Referenced by TOPPASBase::~TOPPASBase().

◆ rename()

static bool rename ( const String from,
const String to,
bool  overwrite_existing = true,
bool  verbose = true 
)
static

Rename a file.

If from and to point to the same file (symlinks are resolved), no action will be taken and true is returned. If the target already exists (and is not identical to the source), this function will fail unless overwrite_existing is true.

Parameters
fromSource filename
toTarget filename
overwrite_existingDelete already existing target, before renaming
verbosePrint message to OPENMS_LOG_ERROR if something goes wrong.
Returns
True on success

◆ validateMatchingFileNames()

static MatchingFileListsStatus validateMatchingFileNames ( const StringList sl1,
const StringList sl2,
bool  basename = true,
bool  ignore_extension = true 
)
static

Helper function to test if filenames provided in two StringLists match.

Passing several InputFilesLists is error-prone as users may provide files in a different order. This helper function performs validation and returns one of three states:

  • MATCH (0): Files match perfectly (considering basename/extension settings)
  • ORDER_MISMATCH (1): Same set of files but in different order
  • SET_MISMATCH (2): Different sets of files (including different counts)
Parameters
sl1First StringList with filenames
sl2Second StringList with filenames
basenameIf set to true, only basenames are compared
ignore_extensionIf set to true, extensions are ignored (e.g., useful to compare spectra filenames to ID filenames)
Returns
MatchingFileListsStatus indicating the validation result

◆ writable()

static bool writable ( const String file)
static

Return true if the file is writable.

Referenced by TOPPViewBase::runTOPPTool_(), and TOPPViewBase::showTOPPDialog_().

Friends And Related Function Documentation

◆ TOPPBase

friend class TOPPBase
friend

Member Data Documentation

◆ temporary_files_

TemporaryFiles_ temporary_files_
staticprivate

private list of temporary filenames, which are deleted upon program exit