46#include <unordered_map>
49#define WIN32_LEAN_AND_MEAN
86 static bool renameFile(
const std::string& src,
const std::string& dst)
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;
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();
341 if (MSwindows::debug)
343 Info<<
"ppid not supported under MSwindows" <<
endl;
354 if (MSwindows::debug)
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);
387 return fileName::validate(
env);
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();
443 name = MSwindows::userName();
479 auto len = ::GetCurrentDirectory(0,
nullptr);
488 len = ::GetCurrentDirectory(len, &(
path[0]));
491 return fileName::validate(
path);
495 <<
"Couldn't get the current working directory"
511 return !dir.empty() && ::SetCurrentDirectory(dir.c_str());;
518 if (pathName.empty())
523 bool ok = ::CreateDirectory(pathName.c_str(), NULL);
531 const DWORD
error = ::GetLastError();
534 case ERROR_ALREADY_EXISTS:
540 case ERROR_PATH_NOT_FOUND:
545 if (parentName.size() &&
mkDir(parentName,
mode))
556 <<
"Couldn't create directory: " << pathName
557 <<
" " << MSwindows::lastError()
568 return !
name.empty() && _chmod(
name.c_str(), m) == 0;
578 if (fileStatus.
valid())
580 return fileStatus.
status().st_mode;
590 ((m != INVALID_FILE_ATTRIBUTES) && (m & FILE_ATTRIBUTE_DIRECTORY))
594 ((m != INVALID_FILE_ATTRIBUTES) && !(m & FILE_ATTRIBUTE_DIRECTORY))
606 return fileName::Type::UNDEFINED;
609 const DWORD m = ::GetFileAttributes(
name.c_str());
613 return fileName::Type::FILE;
617 return fileName::Type::DIRECTORY;
620 return fileName::Type::UNDEFINED;
627 const DWORD m = ::GetFileAttributes((name +
".gz").c_str());
635 const bool checkGzip,
636 const bool followLink
645 const DWORD m = ::GetFileAttributes(
name.c_str());
659 const DWORD m = ::GetFileAttributes(
name.c_str());
668 const bool checkGzip,
669 const bool followLink
678 const DWORD m = ::GetFileAttributes(
name.c_str());
690 if (fileStatus.
valid())
692 return fileStatus.
status().st_size;
719 const bool followLink
724 static constexpr int maxNnames = 100;
727 const bool stripgz = filtergz && (type != fileName::DIRECTORY);
728 const word extgz(
"gz");
738 if (MSwindows::debug)
741 <<
"cannot open directory " << directory <<
endl;
747 if (MSwindows::debug)
750 <<
" : reading directory " << directory <<
endl;
755 dirEntries.
resize(maxNnames);
758 for (; dirIter; ++dirIter)
760 const std::string& item = *dirIter;
772 (type == fileName::DIRECTORY)
773 || (type == fileName::FILE && !fileName::isBackup(
name))
776 if ((directory/
name).type() == type)
778 if (nEntries >= dirEntries.
size())
780 dirEntries.
resize(dirEntries.
size() + maxNnames);
789 dirEntries[nEntries++] =
name;
796 dirEntries.
resize(nEntries);
798 if (nFailed && MSwindows::debug)
801 <<
"Foam::readDir() : reading directory " << directory <<
nl
802 << nFailed <<
" entries with invalid characters in their name"
823 if (srcType == fileName::FILE)
826 if (destFile.
type() == fileName::DIRECTORY)
828 destFile = destFile/src.
name();
854 while (srcStream.get(ch))
860 if (!srcStream.eof() || !destStream)
865 else if (srcType == fileName::DIRECTORY)
867 if (destFile.
type() == fileName::DIRECTORY)
877 if (destFile.
name() != srcDirName)
879 destFile /= srcDirName;
893 if (MSwindows::debug)
895 Info<<
"Copying : " << src/item
896 <<
" to " << destFile/item <<
endl;
914 if (MSwindows::debug)
916 Info<<
"Copying : " << src/item
917 <<
" to " << destFile <<
endl;
938 if (MSwindows::debug)
940 Info<<
"MSwindows does not support ln - softlinking" <<
endl;
949 if (MSwindows::debug)
951 Info<<
"Move : " << src <<
" to " << dst <<
endl;
955 if (src.empty() || dst.empty())
963 dst.
type() == fileName::DIRECTORY
964 && src.
type(followLink) != fileName::DIRECTORY
979 if (src.empty() || ext.empty())
986 constexpr const int maxIndex = 99;
989 for (
int n = 0;
n <= maxIndex; ++
n)
994 sprintf(index,
"%02d",
n);
1000 if (!
exists(dstName,
false) ||
n == maxIndex)
1014 if (MSwindows::debug)
1016 Info<<
"Removing : " << file <<
endl;
1030 0 == std::remove(file.c_str())
1031 || 0 == std::remove((file +
".gz").c_str())
1048 <<
"cannot open directory " << directory <<
endl;
1052 if (MSwindows::debug)
1055 <<
" : removing directory " << directory <<
endl;
1062 for (; dirIter; ++dirIter)
1064 const std::string& item = *dirIter;
1070 const fileName path(fileName::concat(directory, item));
1072 if (
path.type(
false) == fileName::DIRECTORY)
1093 <<
"failed to remove directory " << directory <<
nl
1094 <<
"could not remove " << nErrors <<
" sub-entries" <<
endl;
1099 if (!::RemoveDirectory(directory.c_str()))
1105 <<
"failed to remove directory " << directory <<
endl;
1124 if (::_close(fd) != 0)
1127 <<
"close error on " << fd <<
endl
1135 const std::string& destName,
1136 const label destPort,
1143 if (MSwindows::debug)
1145 Info<<
"MSwindows does not support ping" <<
endl;
1154 return ping(host, 222, timeOut) ||
ping(host, 22, timeOut);
1160 if (MSwindows::debug && bg)
1163 <<
"MSwindows does not support background (fork) tasks" <<
endl;
1166 return std::system(command.c_str());
1172 if (command.
empty())
1180 const int count = command.
size();
1184 for (
int i = 0; i < count; ++i)
1196 if (command.
empty())
1202 const int count = command.
size();
1206 for (
int i = 0; i < count; ++i)
1226 if (MSwindows::debug)
1229 <<
"dlOpen(const fileName&)"
1230 <<
" : dlopen of " << libName << std::endl;
1236 void* handle = ::LoadLibrary(libso.c_str());
1241 && libName.find(
'/') == std::string::npos
1246 libso =
"lib" + libso;
1247 handle = ::LoadLibrary(libso.c_str());
1249 if (MSwindows::debug)
1252 <<
"dlOpen(const fileName&)"
1253 <<
" : dlopen of " << libso << std::endl;
1264 <<
"dlopen error : " << MSwindows::lastError() <<
endl;
1267 if (MSwindows::debug)
1270 <<
"dlOpen(const fileName&)"
1271 <<
" : dlopen of " << libName
1272 <<
" handle " << handle << std::endl;
1287 errorMsg = MSwindows::lastError();
1301 std::initializer_list<fileName> libNames,
1307 for (
const fileName& libName : libNames)
1321 if (MSwindows::debug)
1325 <<
" : dlclose of handle " << handle << std::endl;
1328 const bool ok = ::FreeLibrary(
static_cast<HMODULE
>(handle));
1341 if (!required && (!handle || symbol.empty()))
1346 if (MSwindows::debug)
1349 <<
"dlSymFind(void*, const std::string&, bool)"
1350 <<
" : dlsym of " << symbol << std::endl;
1355 reinterpret_cast<void *
>
1357 ::GetProcAddress(
static_cast<HMODULE
>(handle), symbol.c_str())
1361 if (!fun && required)
1364 <<
"Cannot lookup symbol " << symbol <<
" : "
1365 << MSwindows::lastError() <<
endl;
1378 libs.
append(item.second);
1381 if (MSwindows::debug)
1385 <<
" : determined loaded libraries :" << libs.
size() << std::endl;
Useful combination of include files which define Sin, Sout and Serr and the use of IO streams general...
static std::unordered_map< void *, std::string > libsLoaded
static bool isGzFile(const std::string &name)
Functions used by OpenFOAM that are specific to POSIX compliant operating systems and need to be repl...
An adapter for copying a list of C++ strings into a list of C-style strings for passing to C code tha...
int size() const noexcept
Return the number of C-strings (ie, argc)
bool empty() const noexcept
True if the size (ie, argc) is zero.
A 1D vector of objects of type <T> that resizes itself as necessary to accept the new objects.
void append(const T &val)
Copy append an element to the end of this list.
void resize(const label len)
Adjust allocated size of list.
A simple directory contents iterator.
~directoryIterator()
Destructor.
bool exists() const noexcept
Directory existed for opening.
bool good() const noexcept
Directory pointer is valid.
void close()
Close directory.
directoryIterator(const std::string &dirName, bool allowHidden=false)
Construct for dirName, optionally allowing hidden files/dirs.
const std::string & val() const noexcept
The current item.
bool next()
Read next item, always ignoring "." and ".." entries.
directoryIterator & operator++()
Same as next()
const std::string & operator*() const noexcept
Same as val()
A 1D vector of objects of type <T>, where the size of the vector is known and can be used for subscri...
bool empty() const noexcept
True if the UList is empty (ie, size() is zero)
void size(const label n)
Older name for setAddressableSize.
Class to handle errors and exceptions in a simple, consistent stream-based manner.
A class for handling file names.
Type
Enumerations to handle directory entry types.
Type type(bool followLink=true, bool checkGzip=false) const
fileName lessExt() const
Return file name without extension (part before last .)
word ext() const
Return file name extension (part after last .)
static std::string path(const std::string &str)
Return directory path name (part before last /)
static std::string name(const std::string &str)
Return basename (part beyond last /), including its extension.
Wrapper for stat() and lstat() system calls.
bool valid() const
Was file-stat successful?
time_t modTime() const
Return the modification time in seconds.
double dmodTime() const
Return the modification time in seconds (nanosecond resolution)
const struct stat & status() const
Raw status.
A class for handling character strings derived from std::string.
bool starts_with(const std::string &s) const
True if string starts with the given prefix (cf. C++20)
A class for handling words, derived from Foam::string.
word lessExt() const
Return word without extension (part before last .)
bool hasExt() const
Various checks for extensions.
#define defineTypeNameAndDebug(Type, DebugSwitch)
Define the typeName and debug information.
fileName path(UMean.rootPath()/UMean.caseName()/"graphs"/UMean.instance())
#define FatalErrorInFunction
Report an error message using Foam::FatalError.
#define WarningInFunction
Report a warning using Foam::Warning.
#define InfoInFunction
Report an information message using Foam::Info.
std::string userName()
The user-name from Windows API GetUserName.
std::string lastError()
The last Windows API error from GetLastError.
bool rm(const fileName &file)
Remove a file (or its gz equivalent), returning true if successful.
fileName cwd()
The physical or logical current working directory path name.
string getEnv(const std::string &envName)
Get environment value for given envName.
bool setEnv(const word &name, const std::string &value, const bool overwrite)
Set an environment variable, return true on success.
time_t lastModified(const fileName &name, const bool followLink=true)
Return time of last file modification (normally follows symbolic links).
void fdClose(const int fd)
Close file descriptor.
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 bool const abortHandlerInstalled
int system(const std::string &command, const bool bg=false)
Execute the specified command via the shell.
bool mkDir(const fileName &pathName, mode_t mode=0777)
Make a directory and return an error if it could not be created.
bool isAdministrator()
Is the current user the administrator (root)
bool dlClose(void *handle)
Close a dlopened library using handle. Return true if successful.
bool env(const std::string &envName)
Deprecated(2020-05) check for existence of environment variable.
messageStream Info
Information stream (stdout output on master, null elsewhere)
mode_t mode(const fileName &name, const bool followLink=true)
Return the file mode, normally following symbolic links.
unsigned int sleep(const unsigned int sec)
Sleep for the specified number of seconds.
bool chMod(const fileName &name, const mode_t mode)
Set the file/directory mode, return true on success.
fileName::Type type(const fileName &name, const bool followLink=true)
Return the file type: DIRECTORY or FILE, normally following symbolic links.
static bool renameFile(const std::string &src, const std::string &dst)
string userName()
Return the user's login name.
pid_t pgid()
Return the group PID of this process.
Ostream & endl(Ostream &os)
Add newline and flush stream.
string hostName()
Return the system's host name, as per hostname(1)
bool rmDir(const fileName &directory, const bool silent=false)
Remove a directory and its contents (optionally silencing warnings)
void * dlSymFind(void *handle, const std::string &symbol, bool required=false)
Look for symbol in a dlopened library.
bool ping(const std::string &destName, const label port, const label timeOut)
Check if machine is up by pinging given port.
pid_t ppid()
Return the parent PID of this process.
errorManip< error > abort(error &err)
off_t fileSize(const fileName &name, const bool followLink=true)
Return size of file or -1 on failure (normally follows symbolic links).
double highResLastModified(const fileName &, const bool followLink=true)
Return time of last file modification.
static bool installAbortHandler()
void * dlOpen(const fileName &libName, const bool check=true)
Open a shared library and return handle to library.
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.
pid_t pid()
Return the PID of this process.
bool mvBak(const fileName &src, const std::string &ext="bak")
Rename to a corresponding backup file.
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 cp(const fileName &src, const fileName &dst, const bool followLink=true)
Copy the source to the destination (recursively if necessary).
fileNameList dlLoaded()
Return all loaded libraries.
word name(const expressions::valueTypeCode typeCode)
A word representation of a valueTypeCode. Empty for INVALID.
static void sigAbortHandler(int exitCode)
bool mv(const fileName &src, const fileName &dst, const bool followLink=false)
Rename src to dst.
errorManipArg< error, int > exit(error &err, const int errNo=1)
fileName home()
Return home directory path name for the current user.
string domainName()
Deprecated(2022-01) domain name resolution may be unreliable.
bool ln(const fileName &src, const fileName &dst)
Create a softlink. dst should not exist. Returns true if successful.
bool isDir(const fileName &name, const bool followLink=true)
Does the name exist as a DIRECTORY in the file system?
bool hasEnv(const std::string &envName)
True if environment variable of given name is defined.
constexpr char nl
The newline '\n' character (0x0a)
bool chDir(const fileName &dir)
Change current directory to the one specified and return true on success.