Go to the documentation of this file.
41 #undef DebugInfo // Windows name clash with OpenFOAM messageStream
46 #include <unordered_map>
49 #define WIN32_LEAN_AND_MEAN
88 constexpr
const int flags
91 | MOVEFILE_REPLACE_EXISTING
92 | MOVEFILE_WRITE_THROUGH
97 return ::MoveFileExA(src.c_str(), dst.c_str(), flags);
122 inline bool accept()
const
126 item_.size() && item_ !=
"." && item_ !=
".."
127 && (hidden_ || item_[0] !=
'.')
137 handle_(INVALID_HANDLE_VALUE),
139 hidden_(allowHidden),
142 if (!dirName.empty())
144 WIN32_FIND_DATA findData;
146 handle_ = ::FindFirstFile((dirName/
"*").c_str(), &findData);
151 item_ = findData.cFileName;
181 return (INVALID_HANDLE_VALUE != handle_);
189 ::FindClose(handle_);
190 handle_ = INVALID_HANDLE_VALUE;
195 const std::string&
val()
const
207 WIN32_FIND_DATA findData;
209 while (::FindNextFile(handle_, &findData))
211 item_ = findData.cFileName;
261 DWORD dw = GetLastError();
265 FORMAT_MESSAGE_ALLOCATE_BUFFER |
266 FORMAT_MESSAGE_FROM_SYSTEM |
267 FORMAT_MESSAGE_IGNORE_INSERTS,
270 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
271 reinterpret_cast<LPTSTR
>(&lpMsgBuf),
275 const char* fmt =
"Error %d: %s";
280 int n = ::snprintf(
nullptr, 0, fmt,
static_cast<LPCTSTR
>(lpMsgBuf));
287 n = ::snprintf(&(
output[0]),
n+1, fmt,
static_cast<LPCTSTR
>(lpMsgBuf));
299 const DWORD bufLen = 256;
303 if (::GetUserName(buf, &len))
312 ERROR_INSUFFICIENT_BUFFER == ::GetLastError()
320 ::GetUserName(&(str[0]), &len);
332 const DWORD processId = ::GetCurrentProcessId();
343 Info<<
"ppid not supported under MSwindows" <<
endl;
356 Info<<
"pgid not supported under MSwindows" <<
endl;
366 return !envName.empty() &&
367 ::GetEnvironmentVariable(envName.c_str(),
nullptr, 0);
375 auto len = ::GetEnvironmentVariable(envName.c_str(),
nullptr, 0);
384 len = ::GetEnvironmentVariable(envName.c_str(), &(
env[0]), len);
397 const std::string& value,
405 && ::SetEnvironmentVariable(envName.c_str(), value.c_str())
412 const DWORD bufLen = MAX_COMPUTERNAME_LENGTH + 1;
416 return ::GetComputerName(buf, &len) ? buf :
string();
471 auto len = ::GetCurrentDirectory(0,
nullptr);
480 len = ::GetCurrentDirectory(len, &(
path[0]));
487 <<
"Couldn't get the current working directory"
503 return !dir.empty() && ::SetCurrentDirectory(dir.c_str());;
510 if (pathName.empty())
515 bool ok = ::CreateDirectory(pathName.c_str(), NULL);
523 const DWORD
error = ::GetLastError();
526 case ERROR_ALREADY_EXISTS:
532 case ERROR_PATH_NOT_FOUND:
537 if (parentName.size() &&
mkDir(parentName,
mode))
548 <<
"Couldn't create directory: " << pathName
560 return !
name.empty() && _chmod(
name.c_str(), m) == 0;
570 if (fileStatus.
valid())
572 return fileStatus.
status().st_mode;
581 #define ms_isdir(a) \
582 ((m != INVALID_FILE_ATTRIBUTES) && (m & FILE_ATTRIBUTE_DIRECTORY))
585 #define ms_isreg(s) \
586 ((m != INVALID_FILE_ATTRIBUTES) && !(m & FILE_ATTRIBUTE_DIRECTORY))
598 return fileName::UNDEFINED;
601 const DWORD m = ::GetFileAttributes(
name.c_str());
605 return fileName::FILE;
609 return fileName::DIRECTORY;
612 return fileName::UNDEFINED;
619 const DWORD m = ::GetFileAttributes((
name +
".gz").c_str());
627 const bool checkGzip,
628 const bool followLink
637 const DWORD m = ::GetFileAttributes(
name.c_str());
651 const DWORD m = ::GetFileAttributes(
name.c_str());
660 const bool checkGzip,
661 const bool followLink
670 const DWORD m = ::GetFileAttributes(
name.c_str());
682 if (fileStatus.
valid())
684 return fileStatus.
status().st_size;
711 const bool followLink
716 static constexpr
int maxNnames = 100;
719 const bool stripgz = filtergz && (
type != fileName::DIRECTORY);
720 const word extgz(
"gz");
733 <<
"cannot open directory " << directory <<
endl;
742 <<
" : reading directory " << directory <<
endl;
747 dirEntries.
resize(maxNnames);
750 for (; dirIter; ++dirIter)
752 const std::string& item = *dirIter;
764 (
type == fileName::DIRECTORY)
765 || (
type == fileName::FILE && !fileName::isBackup(
name))
770 if (nEntries >= dirEntries.size())
772 dirEntries.
resize(dirEntries.size() + maxNnames);
781 dirEntries[nEntries++] =
name;
788 dirEntries.
resize(nEntries);
793 <<
"Foam::readDir() : reading directory " << directory <<
nl
794 << nFailed <<
" entries with invalid characters in their name"
815 if (srcType == fileName::FILE)
818 if (destFile.
type() == fileName::DIRECTORY)
820 destFile = destFile/src.
name();
831 std::ifstream srcStream(src, ios_base::in | ios_base::binary);
838 std::ofstream destStream(destFile, ios_base::out | ios_base::binary);
846 while (srcStream.get(ch))
852 if (!srcStream.eof() || !destStream)
857 else if (srcType == fileName::DIRECTORY)
859 if (destFile.
type() == fileName::DIRECTORY)
869 if (destFile.
name() != srcDirName)
871 destFile /= srcDirName;
887 Info<<
"Copying : " << src/item
888 <<
" to " << destFile/item <<
endl;
908 Info<<
"Copying : " << src/item
909 <<
" to " << destFile <<
endl;
932 Info<<
"MSwindows does not support ln - softlinking" <<
endl;
943 Info<<
"Move : " << src <<
" to " << dst <<
endl;
947 if (src.empty() || dst.empty())
955 dst.
type() == fileName::DIRECTORY
956 && src.
type(followLink) != fileName::DIRECTORY
971 if (src.empty() || ext.empty())
978 constexpr
const int maxIndex = 99;
981 for (
int n = 0;
n <= maxIndex; ++
n)
986 sprintf(index,
"%02d",
n);
992 if (!
exists(dstName,
false) ||
n == maxIndex)
1008 Info<<
"Removing : " << file <<
endl;
1022 0 == std::remove(file.c_str())
1023 || 0 == std::remove((file +
".gz").c_str())
1040 <<
"cannot open directory " << directory <<
endl;
1047 <<
" : removing directory " << directory <<
endl;
1054 for (; dirIter; ++dirIter)
1056 const std::string& item = *dirIter;
1062 const fileName path(fileName::concat(directory, item));
1064 if (
path.type(
false) == fileName::DIRECTORY)
1085 <<
"failed to remove directory " << directory <<
nl
1086 <<
"could not remove " << nErrors <<
" sub-entries" <<
endl;
1091 if (!::RemoveDirectory(directory.c_str()))
1097 <<
"failed to remove directory " << directory <<
endl;
1116 if (::_close(fd) != 0)
1119 <<
"close error on " << fd <<
endl
1127 const std::string& destName,
1128 const label destPort,
1137 Info<<
"MSwindows does not support ping" <<
endl;
1146 return ping(host, 222, timeOut) ||
ping(host, 22, timeOut);
1155 <<
"MSwindows does not support background (fork) tasks" <<
endl;
1164 if (command.
empty())
1176 for (
int i = 0; i <
count; ++i)
1188 if (command.
empty())
1198 for (
int i = 0; i <
count; ++i)
1221 <<
"dlOpen(const fileName&)"
1222 <<
" : dlopen of " << libName <<
std::endl;
1228 void* handle = ::LoadLibrary(libso.c_str());
1233 && libName.find(
'/') == std::string::npos
1238 libso =
"lib" + libso;
1239 handle = ::LoadLibrary(libso.c_str());
1244 <<
"dlOpen(const fileName&)"
1245 <<
" : dlopen of " << libso <<
std::endl;
1262 <<
"dlOpen(const fileName&)"
1263 <<
" : dlopen of " << libName
1293 std::initializer_list<fileName> libNames,
1299 for (
const fileName& libName : libNames)
1317 <<
" : dlclose of handle " << handle <<
std::endl;
1320 const bool ok = ::FreeLibrary(
static_cast<HMODULE
>(handle));
1333 if (!required && (!handle || symbol.empty()))
1341 <<
"dlSymFind(void*, const std::string&, bool)"
1342 <<
" : dlsym of " << symbol <<
std::endl;
1347 reinterpret_cast<void *
>
1349 ::GetProcAddress(
static_cast<HMODULE
>(handle), symbol.c_str())
1353 if (!fun && required)
1356 <<
"Cannot lookup symbol " << symbol <<
" : "
1370 libs.
append(item.second);
1377 <<
" : determined loaded libraries :" << libs.size() <<
std::endl;
int debug
Static debugging option.
word lessExt() const
Return word without extension (part before last .)
string domainName()
Return the system's domain name, as per hostname(1) with the '-d' option.
#define InfoInFunction
Report an information message using Foam::Info.
static const bool abortHandlerInstalled
Functions used by OpenFOAM that are specific to POSIX compliant operating systems and need to be repl...
static bool installAbortHandler()
Useful combination of include files which define Sin, Sout and Serr and the use of IO streams general...
bool exists(const fileName &name, const bool checkGzip=true, const bool followLink=true)
Does the name exist (as DIRECTORY or FILE) in the file system?
static Ostream & output(Ostream &os, const IntRange< T > &range)
bool next()
Read next item, always ignoring "." and ".." entries.
A class for handling words, derived from Foam::string.
A class for handling file names.
bool chMod(const fileName &name, const mode_t mode)
Set the file/directory mode, return true on success.
void resize(const label len)
Adjust allocated size of list.
static std::string path(const std::string &str)
Return directory path name (part before last /)
A 1D vector of objects of type <T> that resizes itself as necessary to accept the new objects.
bool starts_with(const std::string &s) const
True if string starts with the given prefix (cf. C++20)
void close()
Close directory.
static std::string name(const std::string &str)
Return basename (part beyond last /), including its extension.
bool exists() const
Directory existed for opening.
int system(const std::string &command, const bool bg=false)
Execute the specified command via the shell.
static void sigAbortHandler(int exitCode)
Type
Enumerations to handle directory entry types.
Wrapper for stat() and lstat() system calls.
bool isFile(const fileName &name, const bool checkGzip=true, const bool followLink=true)
Does the name exist as a FILE in the file system?
bool rm(const fileName &file)
Remove a file (or its gz equivalent), returning true if successful.
Ostream & endl(Ostream &os)
Add newline and flush stream.
void fdClose(const int fd)
Close file descriptor.
bool setEnv(const word &name, const std::string &value, const bool overwrite)
Set an environment variable, return true on success.
fileName lessExt() const
Return file name without extension (part before last .)
A class for handling character strings derived from std::string.
string getEnv(const std::string &envName)
Get environment value for given envName.
pid_t pgid()
Return the group PID of this process.
bool isAdministrator()
Is the current user the administrator (root)
mode_t mode(const fileName &name, const bool followLink=true)
Return the file mode, normally following symbolic links.
bool hasEnv(const std::string &envName)
True if environment variable of given name is defined.
directoryIterator(const fileName &dirName, bool allowHidden=false)
Construct for dirName, optionally allowing hidden files/dirs.
string userName()
Return the user's login name.
off_t fileSize(const fileName &name, const bool followLink=true)
Return size of file or -1 on failure (normally follows symbolic links).
static void check(const int retVal, const char *what)
bool hasExt() const
Various checks for extensions.
void * dlSymFind(void *handle, const std::string &symbol, bool required=false)
Look for symbol in a dlopened library.
messageStream Info
Information stream (stdout output on master, null elsewhere)
DynamicList< T, SizeMin > & append(const T &val)
Append an element to the end of this list.
pid_t pid()
Return the PID of this process.
bool good() const
Directory pointer is valid.
Type type(bool followLink=true, bool checkGzip=false) const
pid_t ppid()
Return the parent PID of this process.
double highResLastModified(const fileName &, const bool followLink=true)
Return time of last file modification.
directoryIterator & operator++()
Same as next()
bool ping(const std::string &destName, const label port, const label timeOut)
Check if machine is up by pinging given port.
bool valid() const
Was file-stat successful?
bool empty() const noexcept
True if the UList is empty (ie, size() is zero)
bool mv(const fileName &src, const fileName &dst, const bool followLink=false)
Rename src to dst.
A simple directory contents iterator.
word ext() const
Return file name extension (part after last .)
std::string lastError()
The last Windows API error from GetLastError.
errorManip< error > abort(error &err)
static bool isGzFile(const std::string &name)
const std::string & operator*() const
Same as val()
errorManipArg< error, int > exit(error &err, const int errNo=1)
bool mvBak(const fileName &src, const std::string &ext="bak")
Rename to a corresponding backup file.
bool chDir(const fileName &dir)
Change current directory to the one specified and return true on success.
fileName home()
Return home directory path name for the current user.
#define FatalErrorInFunction
Report an error message using Foam::FatalError.
const struct stat & status() const
Raw status.
bool cp(const fileName &src, const fileName &dst, const bool followLink=true)
Copy the source to the destination (recursively if necessary).
double dmodTime() const
Return the modification time in seconds (nanosecond resolution)
bool rmDir(const fileName &directory, const bool silent=false)
Remove a directory and its contents (optionally silencing warnings)
unsigned int count(const UList< bool > &bools, const bool val=true)
Count number of 'true' entries.
bool env(const std::string &envName)
Deprecated(2020-05) check for existence of environment variable.
int size() const noexcept
Return the number of C-strings (ie, argc)
time_t modTime() const
Return the modification time in seconds.
fileName::Type type(const fileName &name, const bool followLink=true)
Return the file type: DIRECTORY or FILE, normally following symbolic links.
A 1D vector of objects of type <T>, where the size of the vector is known and can be used for subscri...
fileName path(UMean.rootPath()/UMean.caseName()/"graphs"/UMean.instance())
std::string userName()
The user-name from Windows API GetUserName.
string hostName(bool full=false)
Return the system's host name, as per hostname(1)
bool dlClose(void *handle)
Close a dlopened library using handle. Return true if successful.
static bool renameFile(const fileName &src, const fileName &dst)
word name(const expressions::valueTypeCode typeCode)
A word representation of a valueTypeCode. Empty for INVALID.
bool ln(const fileName &src, const fileName &dst)
Create a softlink. dst should not exist. Returns true if successful.
fileName cwd()
The physical or logical current working directory path name.
static std::unordered_map< void *, std::string > libsLoaded
fileNameList dlLoaded()
Return all loaded libraries.
void size(const label n)
Older name for setAddressableSize.
~directoryIterator()
Destructor.
StringType validate(const std::string &str, const UnaryPredicate &accept, const bool invert=false)
Return a copy of the input string with validated characters.
bool mkDir(const fileName &pathName, mode_t mode=0777)
Make a directory and return an error if it could not be created.
fileNameList readDir(const fileName &directory, const fileName::Type type=fileName::FILE, const bool filtergz=true, const bool followLink=true)
Read a directory and return the entries as a fileName List.
defineTypeNameAndDebug(combustionModel, 0)
#define WarningInFunction
Report a warning using Foam::Warning.
Class to handle errors and exceptions in a simple, consistent stream-based manner.
unsigned int sleep(const unsigned int sec)
Sleep for the specified number of seconds.
void * dlOpen(const fileName &libName, const bool check=true)
Open a shared library and return handle to library.
bool empty() const noexcept
True if the size is zero.
time_t lastModified(const fileName &name, const bool followLink=true)
Return time of last file modification (normally follows symbolic links).
const std::string & val() const
The current item.
bool isDir(const fileName &name, const bool followLink=true)
Does the name exist as a DIRECTORY in the file system?
An adapter for copying a list of C++ strings into a list of C-style strings for passing to C code tha...