31 #include <sys/utime.h> 43 #include <sys/types.h> 45 #if !defined(_MSC_VER) 46 #define _access access 48 #ifndef _stat // It seems MinGW already defines this. 64 int i, dotPos = int(filePath.size());
65 if (filePath.size() < 2)
return string(
"");
67 for (i = (
int)filePath.size() - 1;
68 i >= 0 && !(filePath[i] ==
'\\' || filePath[i] ==
'/'); i--)
69 if (dotPos ==
int(filePath.size()) && filePath[i] ==
'.') dotPos = i;
70 return filePath.substr(i + 1, dotPos - i - 1);
80 if (filePath.size() < 2)
return filePath;
84 for (i = (
int)filePath.size() - 1; i > 0; i--)
85 if (filePath[i] ==
'\\' || filePath[i] ==
'/')
break;
90 return filePath.substr(0, i + 1);
99 const string& filePath,
bool ignore_gz)
101 if (filePath.size() < 2)
return string(
"");
103 size_t i_end = filePath.size() - 1;
105 int i = (int)(i_end);
108 if (filePath[i] ==
'.')
110 string the_ext = filePath.substr(i + 1, i_end - i);
111 if (!ignore_gz || the_ext !=
"gz")
139 std::string path = _path;
142 if (!path.empty() && (*path.rbegin() ==
'/' || *path.rbegin() ==
'\\'))
143 path = path.substr(0, path.size() - 1);
149 if (0 !=
_stat(path.c_str(), &buf))
return false;
152 return 0 != (buf.st_mode & _S_IFDIR);
154 return S_ISDIR(buf.st_mode);
164 bool rc = 0 != CreateDirectoryA(dirName.c_str(),
nullptr);
165 return (rc || GetLastError() == ERROR_ALREADY_EXISTS);
167 int ret = mkdir(dirName.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
168 if (ret && errno != EEXIST)
170 string str =
format(
"[createDirectory %s]", dirName.c_str());
184 return 0 ==
remove(fileName.c_str());
193 size_t len = s.size() + 20;
194 std::vector<char> aux(len);
197 for (
char* c = &aux[0]; *c; c++)
198 if (*c ==
'/') *c =
'\\';
204 int res = ::system(&aux[0]);
209 "[mrpt::system::deleteFiles] Warning: error invoking: `%s`\n",
219 const string& path,
bool deleteDirectoryAsWell)
227 for (
auto& lstFile : lstFiles)
231 if (lstFile.name !=
"." && lstFile.name !=
"..")
234 lstFile.wholePath,
true))
245 if (deleteDirectoryAsWell)
246 return 0 ==
_rmdir(path.c_str());
256 char auxBuf[MAX_PATH] =
"";
257 if (!::GetCurrentDirectoryA(
sizeof(auxBuf) - 1, auxBuf))
259 return std::string(auxBuf);
287 GetSystemTimeAsFileTime(&tt);
288 const UINT uniq =
static_cast<UINT
>(tt.dwLowDateTime);
289 char TMP_PATH[MAX_PATH];
290 char tmpPath[MAX_PATH];
291 GetTempPathA(MAX_PATH, tmpPath);
292 GetTempFileNameA(tmpPath,
"mrpt", uniq, TMP_PATH);
293 return std::string(TMP_PATH);
295 char tmp[] =
"/tmp/mrpt_tempXXXXXX";
300 return std::string(tmp);
310 const string& oldFileName,
const string& newFileName,
311 std::string* error_msg)
313 bool ret_err = 0 == rename(oldFileName.c_str(), newFileName.c_str());
318 *error_msg = strerror(errno);
330 const std::string& filename,
const char replacement_to_invalid_chars)
332 const char forbid[] = {
'<',
'>',
':',
'"',
'/',
'\\',
'|',
'?',
'*'};
333 const unsigned int nForbid =
sizeof(forbid) /
sizeof(forbid[0]);
335 string ret(filename);
338 bool invalid = (c < 32);
340 for (
unsigned int i = 0; !invalid && i < nForbid; i++)
341 if (c == forbid[i]) invalid =
true;
343 if (invalid) c = replacement_to_invalid_chars;
353 #if defined(_MSC_VER) 355 struct __stat64 filStat;
356 if (_stat64(fileName.c_str(), &filStat))
359 return uint64_t(filStat.st_size);
365 if (stat(fileName.c_str(), &filStat))
368 return uint64_t(filStat.st_size);
374 const std::string& filePath,
const std::string& newExtension)
376 if (filePath.size() < 2)
return filePath;
378 const size_t i_end = filePath.size() - 1;
380 for (
int i =
int(i_end); i > 0; i--)
381 if (filePath[i] ==
'.')
return filePath.substr(0, i + 1) + newExtension;
384 return filePath + string(
".") + newExtension;
391 const std::string& sourceFile,
const std::string& targetFile,
392 std::string* outErrStr,
bool copyAttribs)
394 const std::string org =
396 const std::string trg =
407 string(
"Source does not exist or permission denied!: ") + org;
412 if (outErrStr) *outErrStr = string(
"Is source a directory?: ") + org;
417 FILE* f_src =
fopen(org.c_str(),
"rb");
422 "Source file exists but cannot open it... is file " 432 *outErrStr = string(
"Target cannot be a directory: ") + trg;
438 FILE* f_trg =
fopen(trg.c_str(),
"wb");
445 *outErrStr = string(
"Cannot create target file: ") + trg;
455 DWORD dwProp = GetFileAttributesA(trg.c_str());
456 if (dwProp == INVALID_FILE_ATTRIBUTES)
461 "Cannot get file attributes for target file, " 462 "trying to remove a possible read-only attribute " 463 "after first attempt of copy failed, for: ") +
469 dwProp &= ~FILE_ATTRIBUTE_HIDDEN;
470 dwProp &= ~FILE_ATTRIBUTE_READONLY;
471 dwProp &= ~FILE_ATTRIBUTE_SYSTEM;
473 if (!SetFileAttributesA(trg.c_str(), dwProp))
478 "Cannot get file attributes for target file, " 479 "trying to remove a possible read-only attribute " 480 "after first attempt of copy failed, for: ") +
487 f_trg =
fopen(trg.c_str(),
"wb");
492 "Cannot overwrite target file, even after " 493 "changing file attributes! : ") +
500 if (chmod(trg.c_str(), S_IRWXU | S_IRGRP | S_IROTH))
505 "Cannot set file permissions for target file, " 506 "trying to remove a possible read-only attribute " 507 "after first attempt of copy failed, for: ") +
514 f_trg =
fopen(trg.c_str(),
"wb");
519 "Cannot overwrite target file, even after " 520 "changing file permissions! : ") +
532 while (0 != (nBytes = fread(buf, 1, 64 * 1024, f_src)))
534 if (nBytes != fwrite(buf, 1, nBytes, f_trg))
538 "Error writing the contents of the target " 539 "file (disk full?): ") +
555 DWORD dwPropSrc = GetFileAttributesA(org.c_str());
556 if (dwPropSrc == INVALID_FILE_ATTRIBUTES)
561 "Cannot get the file attributes for source file: ") +
565 DWORD dwPropTrg = GetFileAttributesA(trg.c_str());
566 if (dwPropTrg == INVALID_FILE_ATTRIBUTES)
571 "Cannot get the file attributes for target file: ") +
578 dwPropSrc &= FILE_ATTRIBUTE_ARCHIVE | FILE_ATTRIBUTE_HIDDEN |
579 FILE_ATTRIBUTE_NORMAL |
580 FILE_ATTRIBUTE_NOT_CONTENT_INDEXED |
581 FILE_ATTRIBUTE_OFFLINE | FILE_ATTRIBUTE_READONLY |
582 FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_TEMPORARY;
586 ~(FILE_ATTRIBUTE_ARCHIVE | FILE_ATTRIBUTE_HIDDEN |
587 FILE_ATTRIBUTE_NORMAL | FILE_ATTRIBUTE_NOT_CONTENT_INDEXED |
588 FILE_ATTRIBUTE_OFFLINE | FILE_ATTRIBUTE_READONLY |
589 FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_TEMPORARY);
590 dwPropTrg |= dwPropSrc;
593 if (!SetFileAttributesA(trg.c_str(), dwPropTrg))
597 string(
"Cannot set file attributes for target file: ") +
613 const std::string& filePath)
615 std::string ret = filePath;
616 const size_t N = ret.size();
617 for (
size_t i = 0; i < N; i++)
620 if (ret[i] ==
'/') ret[i] =
'\\';
622 if (ret[i] ==
'\\') ret[i] =
'/';
633 if (0 != stat(filename.c_str(), &fS))
639 #include <mrpt/version.h> 646 static vector<string> sPaths;
647 static string sDetectedPath;
648 static bool is_first =
true;
655 string(MRPT_CMAKE_SOURCE_DIR) +
string(
"/share/mrpt/"));
658 string(MRPT_CMAKE_INSTALL_PREFIX) +
string(
"/share/mrpt/"));
664 sBufOk = (0 != GetModuleFileNameA(NULL, buf,
sizeof(buf)));
667 ssize_t nRead = readlink(
"/proc/self/exe", buf,
sizeof(buf));
668 if (nRead >= 0) buf[nRead] =
'\0';
669 sBufOk = (-1 != nRead);
674 string sBuf = string(buf);
675 std::replace(sBuf.begin(), sBuf.end(),
'\\',
'/');
677 sPaths.push_back(sBuf +
string(
"share/mrpt/"));
678 sPaths.push_back(sBuf +
string(
"../share/mrpt/"));
679 sPaths.push_back(sBuf +
string(
"../../share/mrpt/"));
682 for (
const auto& e : sPaths)
689 return sDetectedPath;
static void explore(const std::string &path, const unsigned long mask, TFileInfoList &outList)
The path of the directory to examine must be passed to this constructor, among the According to the f...
bool createDirectory(const std::string &dirName)
Creates a directory.
std::string getShareMRPTDir()
Attempts to find the directory [PREFIX/]share/mrpt/ and returns its absolute path, or empty string if not found.
#define THROW_EXCEPTION(msg)
std::string std::string format(std::string_view fmt, ARGS &&... args)
size_t size(const MATRIXLIKE &m, const int dim)
std::deque< TFileInfo > TFileInfoList
The list type used in "explore".
int void fclose(FILE *f)
An OS-independent version of fclose.
char * strcat(char *dest, size_t destSize, const char *source) noexcept
An OS-independent version of strcat.
bool fileExists(const std::string &fileName)
Test if a given file (or directory) exists.
bool renameFile(const std::string &oldFileName, const std::string &newFileName, std::string *error_msg=nullptr)
Renames a file - If the target path is different and the filesystem allows it, it will be moved to th...
std::string fileNameStripInvalidChars(const std::string &filename, const char replacement_to_invalid_chars='_')
Replace invalid filename chars by underscores ('_') or any other user-given char. ...
#define FILE_ATTRIB_ARCHIVE
#define ASSERT_(f)
Defines an assertion mechanism.
std::string getTempFileName()
Returns the name of a proposed temporary file name.
std::string filePathSeparatorsToNative(const std::string &filePath)
Windows: replace all '/'->'\' , in Linux/MacOS: replace all '\'->'/'.
std::string fileNameChangeExtension(const std::string &filename, const std::string &newExtension)
Replace the filename extension by another one.
void deleteFiles(const std::string &s)
Delete one or more files, especified by the (optional) path and the file name (including '...
std::string extractFileExtension(const std::string &filePath, bool ignore_gz=false)
Extract the extension of a filename.
int fprintf(FILE *fil, const char *format,...) noexcept MRPT_printf_format_check(2
An OS-independent version of fprintf.
This is the global namespace for all Mobile Robot Programming Toolkit (MRPT) libraries.
#define FILE_ATTRIB_DIRECTORY
std::string getcwd()
Returns the current working directory.
bool deleteFile(const std::string &fileName)
Deletes a single file.
bool copyFile(const std::string &sourceFile, const std::string &targetFile, std::string *outErrStr=nullptr, bool copyAttribs=true)
Copies file sourceFile to targetFile.
bool deleteFilesInDirectory(const std::string &s, bool deleteDirectoryAsWell=false)
Delete all the files in a given directory (nothing done if directory does not exists, or path is a file).
FILE * fopen(const char *fileName, const char *mode) noexcept
An OS-independent version of fopen.
bool directoryExists(const std::string &fileName)
Test if a given directory exists (it fails if the given path refers to an existing file)...
uint64_t getFileSize(const std::string &fileName)
Return the size of the given file, or size_t(-1) if some error is found accessing that file...
std::string extractFileName(const std::string &filePath)
Extract just the name (without extension) of a filename from a complete path plus name plus extension...
std::string extractFileDirectory(const std::string &filePath)
Extract the whole path (the directory) of a filename from a complete path plus name plus extension...
int sprintf(char *buf, size_t bufSize, const char *format,...) noexcept MRPT_printf_format_check(3
An OS-independent version of sprintf (Notice the bufSize param, which may be ignored in some compiler...
time_t getFileModificationTime(const std::string &filename)
Return the time of the file last modification, or "0" if the file doesn't exist.