]> git.mxchange.org Git - simgear.git/blob - simgear/misc/sg_path.cxx
WindowsXP workaround for SHGetKnowwFolder
[simgear.git] / simgear / misc / sg_path.cxx
1 // sg_path.cxx -- routines to abstract out path separator differences
2 //               between MacOS and the rest of the world
3 //
4 // Written by Curtis L. Olson, started April 1999.
5 //
6 // Copyright (C) 1999  Curtis L. Olson - http://www.flightgear.org/~curt
7 //
8 // This library is free software; you can redistribute it and/or
9 // modify it under the terms of the GNU Library General Public
10 // License as published by the Free Software Foundation; either
11 // version 2 of the License, or (at your option) any later version.
12 //
13 // This library is distributed in the hope that it will be useful,
14 // but WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 // Library General Public License for more details.
17 //
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the Free Software
20 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
21 //
22 // $Id$
23
24
25 #include <simgear/compiler.h>
26
27 #include <simgear_config.h>
28 #include <simgear/debug/logstream.hxx>
29 #include <simgear/misc/strutils.hxx>
30 #include <stdio.h>
31 #include <sys/stat.h>
32 #include <errno.h>
33 #include <fstream>
34
35 #ifdef _WIN32
36 #  include <direct.h>
37 #endif
38 #include "sg_path.hxx"
39
40 #include <boost/algorithm/string/case_conv.hpp>
41
42 using std::string;
43 using simgear::strutils::starts_with;
44
45 /**
46  * define directory path separators
47  */
48
49 static const char sgDirPathSep = '/';
50 static const char sgDirPathSepBad = '\\';
51
52 #ifdef _WIN32
53 static const char sgSearchPathSep = ';';
54 #else
55 static const char sgSearchPathSep = ':';
56 #endif
57
58 #ifdef _WIN32
59 #include <ShlObj.h>         // for CSIDL
60 #include <versionhelpers.h>
61
62 static SGPath pathForCSIDL(int csidl, const SGPath& def)
63 {
64         typedef BOOL (WINAPI*GetSpecialFolderPath)(HWND, LPSTR, int, BOOL);
65         static GetSpecialFolderPath SHGetSpecialFolderPath = NULL;
66
67         // lazy open+resolve of shell32
68         if (!SHGetSpecialFolderPath) {
69                 HINSTANCE shellDll = ::LoadLibrary("shell32");
70                 SHGetSpecialFolderPath = (GetSpecialFolderPath) GetProcAddress(shellDll, "SHGetSpecialFolderPathA");
71         }
72
73         if (!SHGetSpecialFolderPath){
74                 return def;
75         }
76
77         char path[MAX_PATH];
78         if (SHGetSpecialFolderPath(0, path, csidl, false)) {
79                 return SGPath(path, def.getPermissionChecker());
80         }
81
82         return def;
83 }
84
85 static SGPath pathForKnownFolder(REFKNOWNFOLDERID folderId, const SGPath& def)
86 {
87     typedef HRESULT (WINAPI*PSHGKFP)(REFKNOWNFOLDERID, DWORD, HANDLE, PWSTR*);
88
89     HINSTANCE shellDll = LoadLibrary(TEXT("shell32"));
90     if (shellDll != NULL) {
91         PSHGKFP pSHGetKnownFolderPath = (PSHGKFP) GetProcAddress(shellDll, "SHGetKnownFolderPath");
92         if (pSHGetKnownFolderPath != NULL) {
93             // system call will allocate dynamic memory... which we must release when done
94             wchar_t* localFolder = 0;
95
96             if (pSHGetKnownFolderPath(folderId, KF_FLAG_DEFAULT_PATH, NULL, &localFolder) == S_OK) {
97                 // copy into local memory
98                 char path[MAX_PATH];
99                 size_t len;
100                 if (wcstombs_s(&len, path, localFolder, MAX_PATH) != S_OK) {
101                     path[0] = '\0';
102                     SG_LOG(SG_GENERAL, SG_WARN, "WCS to MBS failed");
103                 }
104
105                 SGPath folder_path = SGPath(path, def.getPermissionChecker());
106
107                 // release dynamic memory
108                 CoTaskMemFree(static_cast<void*>(localFolder));
109
110                 return folder_path;
111             }
112         }
113
114         FreeLibrary(shellDll);
115     }
116
117     return def;
118 }
119
120 #elif __APPLE__
121
122 // defined in CocoaHelpers.mm
123 SGPath appleSpecialFolder(int dirType, int domainMask, const SGPath& def);
124
125 #else
126 static SGPath getXDGDir( const std::string& name,
127                          const SGPath& def,
128                          const std::string& fallback )
129 {
130   // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
131
132   // $XDG_CONFIG_HOME defines the base directory relative to which user specific
133   // configuration files should be stored. If $XDG_CONFIG_HOME is either not set
134   // or empty, a default equal to $HOME/.config should be used.
135   const SGPath user_dirs = SGPath::fromEnv( "XDG_CONFIG_HOME",
136                                             SGPath::home() / ".config")
137                          / "user-dirs.dirs";
138
139   // Format is XDG_xxx_DIR="$HOME/yyy", where yyy is a shell-escaped
140   // homedir-relative path, or XDG_xxx_DIR="/yyy", where /yyy is an absolute
141   // path. No other format is supported.
142   const std::string XDG_ID = "XDG_" + name + "_DIR=\"";
143
144   std::ifstream user_dirs_file( user_dirs.c_str() );
145   std::string line;
146   while( std::getline(user_dirs_file, line).good() )
147   {
148     if( !starts_with(line, XDG_ID) || *line.rbegin() != '"' )
149       continue;
150
151     // Extract dir from XDG_<name>_DIR="<dir>"
152     line = line.substr(XDG_ID.length(), line.length() - XDG_ID.length() - 1 );
153
154     const std::string HOME = "$HOME";
155     if( starts_with(line, HOME) )
156       return SGPath::home(def)
157            / simgear::strutils::unescape(line.substr(HOME.length()));
158
159     return SGPath(line, def.getPermissionChecker());
160   }
161
162   if( def.isNull() )
163     return SGPath::home(def) / fallback;
164
165   return def;
166 }
167 #endif
168
169 // For windows, replace "\" by "/".
170 void
171 SGPath::fix()
172 {
173     string::size_type sz = path.size();
174     for ( string::size_type i = 0; i < sz; ++i ) {
175         if ( path[i] == sgDirPathSepBad ) {
176             path[i] = sgDirPathSep;
177         }
178     }
179     // drop trailing "/"
180     while ((sz>1)&&(path[sz-1]==sgDirPathSep))
181     {
182         path.resize(--sz);
183     }
184 }
185
186
187 // default constructor
188 SGPath::SGPath(PermissionChecker validator)
189     : path(""),
190     _permission_checker(validator),
191     _cached(false),
192     _rwCached(false),
193     _cacheEnabled(true)
194 {
195 }
196
197
198 // create a path based on "path"
199 SGPath::SGPath( const std::string& p, PermissionChecker validator )
200     : path(p),
201     _permission_checker(validator),
202     _cached(false),
203     _rwCached(false),
204     _cacheEnabled(true)
205 {
206     fix();
207 }
208
209 // create a path based on "path" and a "subpath"
210 SGPath::SGPath( const SGPath& p,
211                 const std::string& r,
212                 PermissionChecker validator )
213     : path(p.path),
214     _permission_checker(validator),
215     _cached(false),
216     _rwCached(false),
217     _cacheEnabled(p._cacheEnabled)
218 {
219     append(r);
220     fix();
221 }
222
223 SGPath::SGPath(const SGPath& p) :
224   path(p.path),
225   _permission_checker(p._permission_checker),
226   _cached(p._cached),
227   _rwCached(p._rwCached),
228   _cacheEnabled(p._cacheEnabled),
229   _canRead(p._canRead),
230   _canWrite(p._canWrite),
231   _exists(p._exists),
232   _isDir(p._isDir),
233   _isFile(p._isFile),
234   _modTime(p._modTime)
235 {
236 }
237
238 SGPath& SGPath::operator=(const SGPath& p)
239 {
240   path = p.path;
241   _permission_checker = p._permission_checker,
242   _cached = p._cached;
243   _rwCached = p._rwCached;
244   _cacheEnabled = p._cacheEnabled;
245   _canRead = p._canRead;
246   _canWrite = p._canWrite;
247   _exists = p._exists;
248   _isDir = p._isDir;
249   _isFile = p._isFile;
250   _modTime = p._modTime;
251   return *this;
252 }
253
254 // destructor
255 SGPath::~SGPath() {
256 }
257
258
259 // set path
260 void SGPath::set( const string& p ) {
261     path = p;
262     fix();
263     _cached = false;
264     _rwCached = false;
265 }
266
267 //------------------------------------------------------------------------------
268 void SGPath::setPermissionChecker(PermissionChecker validator)
269 {
270   _permission_checker = validator;
271   _rwCached = false;
272 }
273
274 //------------------------------------------------------------------------------
275 SGPath::PermissionChecker SGPath::getPermissionChecker() const
276 {
277   return _permission_checker;
278 }
279
280 //------------------------------------------------------------------------------
281 void SGPath::set_cached(bool cached)
282 {
283   _cacheEnabled = cached;
284 }
285
286 // append another piece to the existing path
287 void SGPath::append( const string& p ) {
288     if ( path.empty() ) {
289         path = p;
290     } else {
291     if ( p[0] != sgDirPathSep ) {
292         path += sgDirPathSep;
293     }
294         path += p;
295     }
296     fix();
297     _cached = false;
298     _rwCached = false;
299 }
300
301 //------------------------------------------------------------------------------
302 SGPath SGPath::operator/( const std::string& p ) const
303 {
304   SGPath ret = *this;
305   ret.append(p);
306   return ret;
307 }
308
309 //add a new path component to the existing path string
310 void SGPath::add( const string& p ) {
311     append( sgSearchPathSep+p );
312 }
313
314
315 // concatenate a string to the end of the path without inserting a
316 // path separator
317 void SGPath::concat( const string& p ) {
318     if ( path.empty() ) {
319         path = p;
320     } else {
321         path += p;
322     }
323     fix();
324     _cached = false;
325     _rwCached = false;
326 }
327
328
329 // Get the file part of the path (everything after the last path sep)
330 string SGPath::file() const
331 {
332     string::size_type index = path.rfind(sgDirPathSep);
333     if (index != string::npos) {
334         return path.substr(index + 1);
335     } else {
336         return path;
337     }
338 }
339   
340
341 // get the directory part of the path.
342 string SGPath::dir() const {
343     int index = path.rfind(sgDirPathSep);
344     if (index >= 0) {
345         return path.substr(0, index);
346     } else {
347         return "";
348     }
349 }
350
351 // get the base part of the path (everything but the extension.)
352 string SGPath::base() const
353 {
354     string::size_type index = path.rfind(".");
355     string::size_type lastSep = path.rfind(sgDirPathSep);
356     
357 // tolerate dots inside directory names
358     if ((lastSep != string::npos) && (index < lastSep)) {
359         return path;
360     }
361     
362     if (index != string::npos) {
363         return path.substr(0, index);
364     } else {
365         return path;
366     }
367 }
368
369 string SGPath::file_base() const
370 {
371     string::size_type index = path.rfind(sgDirPathSep);
372     if (index == string::npos) {
373         index = 0; // no separator in the name
374     } else {
375         ++index; // skip past the separator
376     }
377     
378     string::size_type firstDot = path.find(".", index);
379     if (firstDot == string::npos) {
380         return path.substr(index); // no extensions
381     }
382     
383     return path.substr(index, firstDot - index);
384 }
385
386 // get the extension (everything after the final ".")
387 // but make sure no "/" follows the "." character (otherwise it
388 // is has to be a directory name containing a ".").
389 string SGPath::extension() const {
390     int index = path.rfind(".");
391     if ((index >= 0)  && (path.find("/", index) == string::npos)) {
392         return path.substr(index + 1);
393     } else {
394         return "";
395     }
396 }
397
398 string SGPath::lower_extension() const {
399     return boost::to_lower_copy(extension());
400 }
401
402 string SGPath::complete_lower_extension() const
403 {
404     string::size_type index = path.rfind(sgDirPathSep);
405     if (index == string::npos) {
406         index = 0; // no separator in the name
407     } else {
408         ++index; // skip past the separator
409     }
410     
411     string::size_type firstDot = path.find(".", index);
412     if ((firstDot != string::npos)  && (path.find(sgDirPathSep, firstDot) == string::npos)) {
413         return boost::to_lower_copy(path.substr(firstDot + 1));
414     } else {
415         return "";
416     }
417 }
418
419 //------------------------------------------------------------------------------
420 void SGPath::validate() const
421 {
422   if (_cached && _cacheEnabled) {
423     return;
424   }
425
426   if (path.empty()) {
427           _exists = false;
428           return;
429   }
430
431 #ifdef _WIN32
432   struct _stat buf ;
433   bool remove_trailing = false;
434   string statPath(path);
435   if ((path.length() > 1) && (path.back() == '/')) {
436           statPath.pop_back();
437   }
438       
439   if (_stat(statPath.c_str(), &buf ) < 0) {
440     _exists = false;
441   } else {
442     _exists = true;
443     _isFile = ((S_IFREG & buf.st_mode ) !=0);
444     _isDir = ((S_IFDIR & buf.st_mode ) !=0);
445     _modTime = buf.st_mtime;
446   }
447
448 #else
449   struct stat buf ;
450
451   if (stat(path.c_str(), &buf ) < 0) {
452     _exists = false;
453   } else {
454     _exists = true;
455     _isFile = ((S_ISREG(buf.st_mode )) != 0);
456     _isDir = ((S_ISDIR(buf.st_mode )) != 0);
457     _modTime = buf.st_mtime;
458   }
459   
460 #endif
461   _cached = true;
462 }
463
464 //------------------------------------------------------------------------------
465 void SGPath::checkAccess() const
466 {
467   if( _rwCached && _cacheEnabled )
468     return;
469
470   if( _permission_checker )
471   {
472     Permissions p = _permission_checker(*this);
473     _canRead = p.read;
474     _canWrite = p.write;
475   }
476   else
477   {
478     _canRead = true;
479     _canWrite = true;
480   }
481
482   _rwCached = true;
483 }
484
485 bool SGPath::exists() const
486 {
487   validate();
488   return _exists;
489 }
490
491 //------------------------------------------------------------------------------
492 bool SGPath::canRead() const
493 {
494   checkAccess();
495   return _canRead;
496 }
497
498 //------------------------------------------------------------------------------
499 bool SGPath::canWrite() const
500 {
501   checkAccess();
502   return _canWrite;
503 }
504
505 bool SGPath::isDir() const
506 {
507   validate();
508   return _exists && _isDir;
509 }
510
511 bool SGPath::isFile() const
512 {
513   validate();
514   return _exists && _isFile;
515 }
516
517 //------------------------------------------------------------------------------
518 #ifdef _WIN32
519 #  define sgMkDir(d,m)       _mkdir(d)
520 #else
521 #  define sgMkDir(d,m)       mkdir(d,m)
522 #endif
523
524 int SGPath::create_dir(mode_t mode)
525 {
526   if( !canWrite() )
527   {
528     SG_LOG( SG_IO,
529             SG_WARN, "Error creating directory for '" << str() << "'"
530                                                     " reason: access denied" );
531     return -3;
532   }
533
534     string_list dirlist = sgPathSplit(dir());
535     if ( dirlist.empty() )
536         return -1;
537     string path = dirlist[0];
538     string_list path_elements = sgPathBranchSplit(path);
539     bool absolute = !path.empty() && path[0] == sgDirPathSep;
540
541     unsigned int i = 1;
542     SGPath dir(absolute ? string( 1, sgDirPathSep ) : "", _permission_checker);
543     dir.concat( path_elements[0] );
544 #ifdef _WIN32
545     if ( dir.str().find(':') != string::npos && path_elements.size() >= 2 ) {
546         dir.append( path_elements[1] );
547         i = 2;
548     }
549 #endif
550   struct stat info;
551   int r;
552   for(; (r = stat(dir.c_str(), &info)) == 0 && i < path_elements.size(); ++i)
553     dir.append(path_elements[i]);
554   if( r == 0 )
555       return 0; // Directory already exists
556
557   for(;;)
558   {
559     if( sgMkDir(dir.c_str(), mode) )
560     {
561       SG_LOG( SG_IO,
562               SG_ALERT, "Error creating directory: (" << dir.str() << ")" );
563       return -2;
564     }
565     else
566       SG_LOG(SG_IO, SG_DEBUG, "Directory created: " << dir.str());
567
568     if( i >= path_elements.size() )
569       return 0;
570
571     dir.append(path_elements[i++]);
572   }
573
574   return 0;
575 }
576
577 string_list sgPathBranchSplit( const string &dirpath ) {
578     string_list path_elements;
579     string element, path = dirpath;
580     while ( ! path.empty() ) {
581         size_t p = path.find( sgDirPathSep );
582         if ( p != string::npos ) {
583             element = path.substr( 0, p );
584             path.erase( 0, p + 1 );
585         } else {
586             element = path;
587             path = "";
588         }
589         if ( ! element.empty() )
590             path_elements.push_back( element );
591     }
592     return path_elements;
593 }
594
595
596 string_list sgPathSplit( const string &search_path ) {
597     string tmp = search_path;
598     string_list result;
599     result.clear();
600
601     bool done = false;
602
603     while ( !done ) {
604         int index = tmp.find(sgSearchPathSep);
605         if (index >= 0) {
606             result.push_back( tmp.substr(0, index) );
607             tmp = tmp.substr( index + 1 );
608         } else {
609             if ( !tmp.empty() )
610                 result.push_back( tmp );
611             done = true;
612         }
613     }
614
615     return result;
616 }
617
618 bool SGPath::isAbsolute() const
619 {
620   if (path.empty()) {
621     return false;
622   }
623   
624 #ifdef _WIN32
625   // detect '[A-Za-z]:/'
626   if (path.size() > 2) {
627     if (isalpha(path[0]) && (path[1] == ':') && (path[2] == sgDirPathSep)) {
628       return true;
629     }
630   }
631 #endif
632   
633   return (path[0] == sgDirPathSep);
634 }
635
636 bool SGPath::isNull() const
637 {
638   return path.empty();
639 }
640
641 std::string SGPath::str_native() const
642 {
643 #ifdef _WIN32
644     std::string s = str();
645     std::string::size_type pos;
646     std::string nativeSeparator;
647     nativeSeparator = sgDirPathSepBad;
648
649     while( (pos=s.find( sgDirPathSep )) != std::string::npos ) {
650         s.replace( pos, 1, nativeSeparator );
651     }
652     return s;
653 #else
654     return str();
655 #endif
656 }
657
658 //------------------------------------------------------------------------------
659 bool SGPath::remove()
660 {
661   if( !canWrite() )
662   {
663     SG_LOG( SG_IO, SG_WARN, "file remove failed: (" << str() << ")"
664                                                " reason: access denied" );
665     return false;
666   }
667
668   int err = ::unlink(c_str());
669   if( err )
670   {
671     SG_LOG( SG_IO, SG_WARN, "file remove failed: (" << str() << ") "
672                                                " reason: " << strerror(errno) );
673     // TODO check if failed unlink can really change any of the cached values
674   }
675
676   _cached = false; // stat again if required
677   _rwCached = false;
678   return (err == 0);
679 }
680
681 time_t SGPath::modTime() const
682 {
683     validate();
684     return _modTime;
685 }
686
687 bool SGPath::operator==(const SGPath& other) const
688 {
689     return (path == other.path);
690 }
691
692 bool SGPath::operator!=(const SGPath& other) const
693 {
694     return (path != other.path);
695 }
696
697 //------------------------------------------------------------------------------
698 bool SGPath::rename(const SGPath& newName)
699 {
700   if( !canRead() || !canWrite() || !newName.canWrite() )
701   {
702     SG_LOG( SG_IO, SG_WARN, "rename failed: from " << str() <<
703                                             " to " << newName.str() <<
704                                             " reason: access denied" );
705     return false;
706   }
707
708 #ifdef SG_WINDOWS
709         if (newName.exists()) {
710                 SGPath r(newName);
711                 if (!r.remove()) {
712                         return false;
713                 }
714         }
715 #endif
716   if( ::rename(c_str(), newName.c_str()) != 0 )
717   {
718     SG_LOG( SG_IO, SG_WARN, "rename failed: from " << str() <<
719                                             " to " << newName.str() <<
720                                             " reason: " << strerror(errno) );
721     return false;
722   }
723
724   path = newName.path;
725
726   // Do not remove permission checker (could happen for example if just using
727   // a std::string as new name)
728   if( newName._permission_checker )
729     _permission_checker = newName._permission_checker;
730
731   _cached = false;
732   _rwCached = false;
733
734   return true;
735 }
736
737 //------------------------------------------------------------------------------
738 SGPath SGPath::standardLocation(StandardLocation type, const SGPath& def)
739 {
740   switch(type)
741   {
742     case HOME:
743       return home(def);
744
745 #ifdef _WIN32
746     case DESKTOP:
747         if (IsWindowsVistaOrGreater())
748             return pathForKnownFolder(FOLDERID_Desktop, def);
749
750         return pathForCSIDL(CSIDL_DESKTOPDIRECTORY, def);
751
752     case DOWNLOADS:
753         if (IsWindowsVistaOrGreater())
754             return pathForKnownFolder(FOLDERID_Downloads, def);
755
756         if (!def.isNull())
757             return def;
758
759         return pathForCSIDL(CSIDL_DESKTOPDIRECTORY, def);
760
761     case DOCUMENTS:
762         if (IsWindowsVistaOrGreater())
763             return pathForKnownFolder(FOLDERID_Documents, def);
764
765         return pathForCSIDL(CSIDL_MYDOCUMENTS, def);
766
767     case PICTURES:
768         if (IsWindowsVistaOrGreater())
769             return pathForKnownFolder(FOLDERID_Pictures, def);
770
771         return pathForCSIDL(CSIDL_MYPICTURES, def);
772
773 #elif __APPLE__
774       // since this is C++, we can't include NSPathUtilities.h to access the enum
775       // values, so hard-coding them here (they are stable, don't worry)
776     case DOWNLOADS:
777       return appleSpecialFolder(15, 1, def);
778     case DESKTOP:
779       return appleSpecialFolder(12, 1, def);
780     case DOCUMENTS:
781       return appleSpecialFolder(9, 1, def);
782     case PICTURES:
783       return appleSpecialFolder(19, 1, def);
784 #else
785     case DESKTOP:
786       return getXDGDir("DESKTOP", def, "Desktop");
787     case DOWNLOADS:
788       return getXDGDir("DOWNLOADS", def, "Downloads");
789     case DOCUMENTS:
790       return getXDGDir("DOCUMENTS", def, "Documents");
791     case PICTURES:
792       return getXDGDir("PICTURES", def, "Pictures");
793 #endif
794     default:
795       SG_LOG( SG_GENERAL,
796               SG_WARN,
797               "SGPath::standardLocation() unhandled type: " << type );
798       return def;
799   }
800 }
801
802 //------------------------------------------------------------------------------
803 SGPath SGPath::fromEnv(const char* name, const SGPath& def)
804 {
805   const char* val = getenv(name);
806   if( val && val[0] )
807     return SGPath(val, def._permission_checker);
808   return def;
809 }
810
811 //------------------------------------------------------------------------------
812 SGPath SGPath::home(const SGPath& def)
813 {
814 #ifdef _WIN32
815     return fromEnv("USERPROFILE", def);
816 #else
817     return fromEnv("HOME", def);
818 #endif
819 }
820
821 //------------------------------------------------------------------------------
822 SGPath SGPath::desktop(const SGPath& def)
823 {
824   return standardLocation(DESKTOP, def);
825 }
826
827 //------------------------------------------------------------------------------
828 SGPath SGPath::documents(const SGPath& def)
829 {
830   return standardLocation(DOCUMENTS, def);
831 }
832
833 //------------------------------------------------------------------------------
834 std::string SGPath::realpath() const
835 {
836 #if (defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED <= 1050)
837     // Workaround for Mac OS 10.5. Somehow fgfs crashes on Mac at ::realpath. 
838     // This means relative paths cannot be used on Mac OS <= 10.5
839     return path;
840 #else
841   #if defined(_MSC_VER) /*for MS compilers */ || defined(_WIN32) /*needed for non MS windows compilers like MingW*/
842     // with absPath NULL, will allocate, and ignore length
843     char *buf = _fullpath( NULL, path.c_str(), _MAX_PATH );
844   #else
845     // POSIX
846     char* buf = ::realpath(path.c_str(), NULL);
847   #endif
848     if (!buf)
849     {
850         SG_LOG(SG_IO, SG_ALERT, "ERROR: The path '" << path << "' does not exist in the file system.");
851         return path;
852     }
853     std::string p(buf);
854     free(buf);
855     return p;
856 #endif
857 }