1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/filename.cpp
3 // Purpose: wxFileName - encapsulates a file path
4 // Author: Robert Roebling, Vadim Zeitlin
8 // Copyright: (c) 2000 Robert Roebling
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
13 Here are brief descriptions of the filename formats supported by this class:
15 wxPATH_UNIX: standard Unix format, used under Darwin as well, absolute file
17 /dir1/dir2/.../dirN/filename, "." and ".." stand for the
18 current and parent directory respectively, "~" is parsed as the
19 user HOME and "~username" as the HOME of that user
21 wxPATH_DOS: DOS/Windows format, absolute file names have the form:
22 drive:\dir1\dir2\...\dirN\filename.ext where drive is a single
23 letter. "." and ".." as for Unix but no "~".
25 There are also UNC names of the form \\share\fullpath
27 wxPATH_MAC: Mac OS 8/9 and Mac OS X under CodeWarrior 7 format, absolute file
29 volume:dir1:...:dirN:filename
30 and the relative file names are either
31 :dir1:...:dirN:filename
34 (although :filename works as well).
35 Since the volume is just part of the file path, it is not
36 treated like a separate entity as it is done under DOS and
37 VMS, it is just treated as another dir.
39 wxPATH_VMS: VMS native format, absolute file names have the form
40 <device>:[dir1.dir2.dir3]file.txt
42 <device>:[000000.dir1.dir2.dir3]file.txt
44 the <device> is the physical device (i.e. disk). 000000 is the
45 root directory on the device which can be omitted.
47 Note that VMS uses different separators unlike Unix:
48 : always after the device. If the path does not contain : than
49 the default (the device of the current directory) is assumed.
50 [ start of directory specification
51 . separator between directory and subdirectory
52 ] between directory and file
55 // ============================================================================
57 // ============================================================================
59 // ----------------------------------------------------------------------------
61 // ----------------------------------------------------------------------------
63 // For compilers that support precompilation, includes "wx.h".
64 #include "wx/wxprec.h"
72 #include "wx/msw/wrapwin.h" // For GetShort/LongPathName
74 #include "wx/dynarray.h"
81 #include "wx/filename.h"
82 #include "wx/private/filename.h"
83 #include "wx/tokenzr.h"
84 #include "wx/config.h" // for wxExpandEnvVars
85 #include "wx/dynlib.h"
88 #if defined(__WIN32__) && defined(__MINGW32__)
89 #include "wx/msw/gccpriv.h"
93 #include "wx/msw/private.h"
96 #if defined(__WXMAC__)
97 #include "wx/osx/private.h" // includes mac headers
100 // utime() is POSIX so should normally be available on all Unices
102 #include <sys/types.h>
104 #include <sys/stat.h>
114 #include <sys/types.h>
116 #include <sys/stat.h>
127 #include <sys/utime.h>
128 #include <sys/stat.h>
139 #define MAX_PATH _MAX_PATH
144 extern const wxULongLong wxInvalidSize
= (unsigned)-1;
145 #endif // wxUSE_LONGLONG
150 // ----------------------------------------------------------------------------
152 // ----------------------------------------------------------------------------
154 // small helper class which opens and closes the file - we use it just to get
155 // a file handle for the given file name to pass it to some Win32 API function
156 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
167 wxFileHandle(const wxString
& filename
, OpenMode mode
, int flags
= 0)
169 // be careful and use FILE_{READ,WRITE}_ATTRIBUTES here instead of the
170 // usual GENERIC_{READ,WRITE} as we don't want the file access time to
171 // be changed when we open it because this class is used for setting
172 // access time (see #10567)
173 m_hFile
= ::CreateFile
175 filename
.fn_str(), // name
176 mode
== ReadAttr
? FILE_READ_ATTRIBUTES
// access mask
177 : FILE_WRITE_ATTRIBUTES
,
178 FILE_SHARE_READ
| // sharing mode
179 FILE_SHARE_WRITE
, // (allow everything)
180 NULL
, // no secutity attr
181 OPEN_EXISTING
, // creation disposition
183 NULL
// no template file
186 if ( m_hFile
== INVALID_HANDLE_VALUE
)
188 if ( mode
== ReadAttr
)
190 wxLogSysError(_("Failed to open '%s' for reading"),
195 wxLogSysError(_("Failed to open '%s' for writing"),
203 if ( m_hFile
!= INVALID_HANDLE_VALUE
)
205 if ( !::CloseHandle(m_hFile
) )
207 wxLogSysError(_("Failed to close file handle"));
212 // return true only if the file could be opened successfully
213 bool IsOk() const { return m_hFile
!= INVALID_HANDLE_VALUE
; }
216 operator HANDLE() const { return m_hFile
; }
224 // ----------------------------------------------------------------------------
226 // ----------------------------------------------------------------------------
228 #if wxUSE_DATETIME && defined(__WIN32__) && !defined(__WXMICROWIN__)
230 // convert between wxDateTime and FILETIME which is a 64-bit value representing
231 // the number of 100-nanosecond intervals since January 1, 1601.
233 static void ConvertFileTimeToWx(wxDateTime
*dt
, const FILETIME
&ft
)
235 FILETIME ftcopy
= ft
;
237 if ( !::FileTimeToLocalFileTime(&ftcopy
, &ftLocal
) )
239 wxLogLastError(wxT("FileTimeToLocalFileTime"));
243 if ( !::FileTimeToSystemTime(&ftLocal
, &st
) )
245 wxLogLastError(wxT("FileTimeToSystemTime"));
248 dt
->Set(st
.wDay
, wxDateTime::Month(st
.wMonth
- 1), st
.wYear
,
249 st
.wHour
, st
.wMinute
, st
.wSecond
, st
.wMilliseconds
);
252 static void ConvertWxToFileTime(FILETIME
*ft
, const wxDateTime
& dt
)
255 st
.wDay
= dt
.GetDay();
256 st
.wMonth
= (WORD
)(dt
.GetMonth() + 1);
257 st
.wYear
= (WORD
)dt
.GetYear();
258 st
.wHour
= dt
.GetHour();
259 st
.wMinute
= dt
.GetMinute();
260 st
.wSecond
= dt
.GetSecond();
261 st
.wMilliseconds
= dt
.GetMillisecond();
264 if ( !::SystemTimeToFileTime(&st
, &ftLocal
) )
266 wxLogLastError(wxT("SystemTimeToFileTime"));
269 if ( !::LocalFileTimeToFileTime(&ftLocal
, ft
) )
271 wxLogLastError(wxT("LocalFileTimeToFileTime"));
275 #endif // wxUSE_DATETIME && __WIN32__
277 // return a string with the volume par
278 static wxString
wxGetVolumeString(const wxString
& volume
, wxPathFormat format
)
282 if ( !volume
.empty() )
284 format
= wxFileName::GetFormat(format
);
286 // Special Windows UNC paths hack, part 2: undo what we did in
287 // SplitPath() and make an UNC path if we have a drive which is not a
288 // single letter (hopefully the network shares can't be one letter only
289 // although I didn't find any authoritative docs on this)
290 if ( format
== wxPATH_DOS
&& volume
.length() > 1 )
292 path
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_DOS
<< volume
;
294 else if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
296 path
<< volume
<< wxFileName::GetVolumeSeparator(format
);
304 // return true if the character is a DOS path separator i.e. either a slash or
306 inline bool IsDOSPathSep(wxUniChar ch
)
308 return ch
== wxFILE_SEP_PATH_DOS
|| ch
== wxFILE_SEP_PATH_UNIX
;
311 // return true if the format used is the DOS/Windows one and the string looks
313 static bool IsUNCPath(const wxString
& path
, wxPathFormat format
)
315 return format
== wxPATH_DOS
&&
316 path
.length() >= 4 && // "\\a" can't be a UNC path
317 IsDOSPathSep(path
[0u]) &&
318 IsDOSPathSep(path
[1u]) &&
319 !IsDOSPathSep(path
[2u]);
322 } // anonymous namespace
324 // ============================================================================
326 // ============================================================================
328 // ----------------------------------------------------------------------------
329 // wxFileName construction
330 // ----------------------------------------------------------------------------
332 void wxFileName::Assign( const wxFileName
&filepath
)
334 m_volume
= filepath
.GetVolume();
335 m_dirs
= filepath
.GetDirs();
336 m_name
= filepath
.GetName();
337 m_ext
= filepath
.GetExt();
338 m_relative
= filepath
.m_relative
;
339 m_hasExt
= filepath
.m_hasExt
;
342 void wxFileName::Assign(const wxString
& volume
,
343 const wxString
& path
,
344 const wxString
& name
,
349 // we should ignore paths which look like UNC shares because we already
350 // have the volume here and the UNC notation (\\server\path) is only valid
351 // for paths which don't start with a volume, so prevent SetPath() from
352 // recognizing "\\foo\bar" in "c:\\foo\bar" as an UNC path
354 // note also that this is a rather ugly way to do what we want (passing
355 // some kind of flag telling to ignore UNC paths to SetPath() would be
356 // better) but this is the safest thing to do to avoid breaking backwards
357 // compatibility in 2.8
358 if ( IsUNCPath(path
, format
) )
360 // remove one of the 2 leading backslashes to ensure that it's not
361 // recognized as an UNC path by SetPath()
362 wxString
pathNonUNC(path
, 1, wxString::npos
);
363 SetPath(pathNonUNC
, format
);
365 else // no UNC complications
367 SetPath(path
, format
);
377 void wxFileName::SetPath( const wxString
& pathOrig
, wxPathFormat format
)
381 if ( pathOrig
.empty() )
389 format
= GetFormat( format
);
391 // 0) deal with possible volume part first
394 SplitVolume(pathOrig
, &volume
, &path
, format
);
395 if ( !volume
.empty() )
402 // 1) Determine if the path is relative or absolute.
406 // we had only the volume
410 wxChar leadingChar
= path
[0u];
415 m_relative
= leadingChar
== wxT(':');
417 // We then remove a leading ":". The reason is in our
418 // storage form for relative paths:
419 // ":dir:file.txt" actually means "./dir/file.txt" in
420 // DOS notation and should get stored as
421 // (relative) (dir) (file.txt)
422 // "::dir:file.txt" actually means "../dir/file.txt"
423 // stored as (relative) (..) (dir) (file.txt)
424 // This is important only for the Mac as an empty dir
425 // actually means <UP>, whereas under DOS, double
426 // slashes can be ignored: "\\\\" is the same as "\\".
432 // TODO: what is the relative path format here?
437 wxFAIL_MSG( wxT("Unknown path format") );
438 // !! Fall through !!
441 m_relative
= leadingChar
!= wxT('/');
445 m_relative
= !IsPathSeparator(leadingChar
, format
);
450 // 2) Break up the path into its members. If the original path
451 // was just "/" or "\\", m_dirs will be empty. We know from
452 // the m_relative field, if this means "nothing" or "root dir".
454 wxStringTokenizer
tn( path
, GetPathSeparators(format
) );
456 while ( tn
.HasMoreTokens() )
458 wxString token
= tn
.GetNextToken();
460 // Remove empty token under DOS and Unix, interpret them
464 if (format
== wxPATH_MAC
)
465 m_dirs
.Add( wxT("..") );
475 void wxFileName::Assign(const wxString
& fullpath
,
478 wxString volume
, path
, name
, ext
;
480 SplitPath(fullpath
, &volume
, &path
, &name
, &ext
, &hasExt
, format
);
482 Assign(volume
, path
, name
, ext
, hasExt
, format
);
485 void wxFileName::Assign(const wxString
& fullpathOrig
,
486 const wxString
& fullname
,
489 // always recognize fullpath as directory, even if it doesn't end with a
491 wxString fullpath
= fullpathOrig
;
492 if ( !fullpath
.empty() && !wxEndsWithPathSeparator(fullpath
) )
494 fullpath
+= GetPathSeparator(format
);
497 wxString volume
, path
, name
, ext
;
500 // do some consistency checks: the name should be really just the filename
501 // and the path should be really just a path
502 wxString volDummy
, pathDummy
, nameDummy
, extDummy
;
504 SplitPath(fullname
, &volDummy
, &pathDummy
, &name
, &ext
, &hasExt
, format
);
506 wxASSERT_MSG( volDummy
.empty() && pathDummy
.empty(),
507 wxT("the file name shouldn't contain the path") );
509 SplitPath(fullpath
, &volume
, &path
, &nameDummy
, &extDummy
, format
);
512 // This test makes no sense on an OpenVMS system.
513 wxASSERT_MSG( nameDummy
.empty() && extDummy
.empty(),
514 wxT("the path shouldn't contain file name nor extension") );
516 Assign(volume
, path
, name
, ext
, hasExt
, format
);
519 void wxFileName::Assign(const wxString
& pathOrig
,
520 const wxString
& name
,
526 SplitVolume(pathOrig
, &volume
, &path
, format
);
528 Assign(volume
, path
, name
, ext
, format
);
531 void wxFileName::AssignDir(const wxString
& dir
, wxPathFormat format
)
533 Assign(dir
, wxEmptyString
, format
);
536 void wxFileName::Clear()
542 m_ext
= wxEmptyString
;
544 // we don't have any absolute path for now
552 wxFileName
wxFileName::FileName(const wxString
& file
, wxPathFormat format
)
554 return wxFileName(file
, format
);
558 wxFileName
wxFileName::DirName(const wxString
& dir
, wxPathFormat format
)
561 fn
.AssignDir(dir
, format
);
565 // ----------------------------------------------------------------------------
567 // ----------------------------------------------------------------------------
569 bool wxFileName::FileExists() const
571 return wxFileName::FileExists( GetFullPath() );
574 bool wxFileName::FileExists( const wxString
&file
)
576 return ::wxFileExists( file
);
579 bool wxFileName::DirExists() const
581 return wxFileName::DirExists( GetPath() );
584 bool wxFileName::DirExists( const wxString
&dir
)
586 return ::wxDirExists( dir
);
589 // ----------------------------------------------------------------------------
590 // CWD and HOME stuff
591 // ----------------------------------------------------------------------------
593 void wxFileName::AssignCwd(const wxString
& volume
)
595 AssignDir(wxFileName::GetCwd(volume
));
599 wxString
wxFileName::GetCwd(const wxString
& volume
)
601 // if we have the volume, we must get the current directory on this drive
602 // and to do this we have to chdir to this volume - at least under Windows,
603 // I don't know how to get the current drive on another volume elsewhere
606 if ( !volume
.empty() )
609 SetCwd(volume
+ GetVolumeSeparator());
612 wxString cwd
= ::wxGetCwd();
614 if ( !volume
.empty() )
622 bool wxFileName::SetCwd() const
624 return wxFileName::SetCwd( GetPath() );
627 bool wxFileName::SetCwd( const wxString
&cwd
)
629 return ::wxSetWorkingDirectory( cwd
);
632 void wxFileName::AssignHomeDir()
634 AssignDir(wxFileName::GetHomeDir());
637 wxString
wxFileName::GetHomeDir()
639 return ::wxGetHomeDir();
643 // ----------------------------------------------------------------------------
644 // CreateTempFileName
645 // ----------------------------------------------------------------------------
647 #if wxUSE_FILE || wxUSE_FFILE
650 #if !defined wx_fdopen && defined HAVE_FDOPEN
651 #define wx_fdopen fdopen
654 // NB: GetTempFileName() under Windows creates the file, so using
655 // O_EXCL there would fail
657 #define wxOPEN_EXCL 0
659 #define wxOPEN_EXCL O_EXCL
663 #ifdef wxOpenOSFHandle
664 #define WX_HAVE_DELETE_ON_CLOSE
665 // On Windows create a file with the FILE_FLAGS_DELETE_ON_CLOSE flags.
667 static int wxOpenWithDeleteOnClose(const wxString
& filename
)
669 DWORD access
= GENERIC_READ
| GENERIC_WRITE
;
671 DWORD disposition
= OPEN_ALWAYS
;
673 DWORD attributes
= FILE_ATTRIBUTE_TEMPORARY
|
674 FILE_FLAG_DELETE_ON_CLOSE
;
676 HANDLE h
= ::CreateFile(filename
.fn_str(), access
, 0, NULL
,
677 disposition
, attributes
, NULL
);
679 return wxOpenOSFHandle(h
, wxO_BINARY
);
681 #endif // wxOpenOSFHandle
684 // Helper to open the file
686 static int wxTempOpen(const wxString
& path
, bool *deleteOnClose
)
688 #ifdef WX_HAVE_DELETE_ON_CLOSE
690 return wxOpenWithDeleteOnClose(path
);
693 *deleteOnClose
= false;
695 return wxOpen(path
, wxO_BINARY
| O_RDWR
| O_CREAT
| wxOPEN_EXCL
, 0600);
700 // Helper to open the file and attach it to the wxFFile
702 static bool wxTempOpen(wxFFile
*file
, const wxString
& path
, bool *deleteOnClose
)
705 *deleteOnClose
= false;
706 return file
->Open(path
, wxT("w+b"));
708 int fd
= wxTempOpen(path
, deleteOnClose
);
711 file
->Attach(wx_fdopen(fd
, "w+b"));
712 return file
->IsOpened();
715 #endif // wxUSE_FFILE
719 #define WXFILEARGS(x, y) y
721 #define WXFILEARGS(x, y) x
723 #define WXFILEARGS(x, y) x, y
727 // Implementation of wxFileName::CreateTempFileName().
729 static wxString
wxCreateTempImpl(
730 const wxString
& prefix
,
731 WXFILEARGS(wxFile
*fileTemp
, wxFFile
*ffileTemp
),
732 bool *deleteOnClose
= NULL
)
734 #if wxUSE_FILE && wxUSE_FFILE
735 wxASSERT(fileTemp
== NULL
|| ffileTemp
== NULL
);
737 wxString path
, dir
, name
;
738 bool wantDeleteOnClose
= false;
742 // set the result to false initially
743 wantDeleteOnClose
= *deleteOnClose
;
744 *deleteOnClose
= false;
748 // easier if it alwasys points to something
749 deleteOnClose
= &wantDeleteOnClose
;
752 // use the directory specified by the prefix
753 wxFileName::SplitPath(prefix
, &dir
, &name
, NULL
/* extension */);
757 dir
= wxFileName::GetTempDir();
760 #if defined(__WXWINCE__)
761 path
= dir
+ wxT("\\") + name
;
763 while (wxFileName::FileExists(path
))
765 path
= dir
+ wxT("\\") + name
;
770 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
771 if ( !::GetTempFileName(dir
.fn_str(), name
.fn_str(), 0,
772 wxStringBuffer(path
, MAX_PATH
+ 1)) )
774 wxLogLastError(wxT("GetTempFileName"));
782 if ( !wxEndsWithPathSeparator(dir
) &&
783 (name
.empty() || !wxIsPathSeparator(name
[0u])) )
785 path
+= wxFILE_SEP_PATH
;
790 #if defined(HAVE_MKSTEMP)
791 // scratch space for mkstemp()
792 path
+= wxT("XXXXXX");
794 // we need to copy the path to the buffer in which mkstemp() can modify it
795 wxCharBuffer
buf(path
.fn_str());
797 // cast is safe because the string length doesn't change
798 int fdTemp
= mkstemp( (char*)(const char*) buf
);
801 // this might be not necessary as mkstemp() on most systems should have
802 // already done it but it doesn't hurt neither...
805 else // mkstemp() succeeded
807 path
= wxConvFile
.cMB2WX( (const char*) buf
);
810 // avoid leaking the fd
813 fileTemp
->Attach(fdTemp
);
822 ffileTemp
->Attach(wx_fdopen(fdTemp
, "r+b"));
824 ffileTemp
->Open(path
, wxT("r+b"));
835 #else // !HAVE_MKSTEMP
839 path
+= wxT("XXXXXX");
841 wxCharBuffer buf
= wxConvFile
.cWX2MB( path
);
842 if ( !mktemp( (char*)(const char*) buf
) )
848 path
= wxConvFile
.cMB2WX( (const char*) buf
);
850 #else // !HAVE_MKTEMP (includes __DOS__)
851 // generate the unique file name ourselves
852 #if !defined(__DOS__) && !defined(__PALMOS__) && (!defined(__MWERKS__) || defined(__DARWIN__) )
853 path
<< (unsigned int)getpid();
858 static const size_t numTries
= 1000;
859 for ( size_t n
= 0; n
< numTries
; n
++ )
861 // 3 hex digits is enough for numTries == 1000 < 4096
862 pathTry
= path
+ wxString::Format(wxT("%.03x"), (unsigned int) n
);
863 if ( !wxFileName::FileExists(pathTry
) )
872 #endif // HAVE_MKTEMP/!HAVE_MKTEMP
874 #endif // HAVE_MKSTEMP/!HAVE_MKSTEMP
876 #endif // Windows/!Windows
880 wxLogSysError(_("Failed to create a temporary file name"));
886 // open the file - of course, there is a race condition here, this is
887 // why we always prefer using mkstemp()...
889 if ( fileTemp
&& !fileTemp
->IsOpened() )
891 *deleteOnClose
= wantDeleteOnClose
;
892 int fd
= wxTempOpen(path
, deleteOnClose
);
894 fileTemp
->Attach(fd
);
901 if ( ffileTemp
&& !ffileTemp
->IsOpened() )
903 *deleteOnClose
= wantDeleteOnClose
;
904 ok
= wxTempOpen(ffileTemp
, path
, deleteOnClose
);
910 // FIXME: If !ok here should we loop and try again with another
911 // file name? That is the standard recourse if open(O_EXCL)
912 // fails, though of course it should be protected against
913 // possible infinite looping too.
915 wxLogError(_("Failed to open temporary file."));
925 static bool wxCreateTempImpl(
926 const wxString
& prefix
,
927 WXFILEARGS(wxFile
*fileTemp
, wxFFile
*ffileTemp
),
930 bool deleteOnClose
= true;
932 *name
= wxCreateTempImpl(prefix
,
933 WXFILEARGS(fileTemp
, ffileTemp
),
936 bool ok
= !name
->empty();
941 else if (ok
&& wxRemoveFile(*name
))
949 static void wxAssignTempImpl(
951 const wxString
& prefix
,
952 WXFILEARGS(wxFile
*fileTemp
, wxFFile
*ffileTemp
))
955 tempname
= wxCreateTempImpl(prefix
, WXFILEARGS(fileTemp
, ffileTemp
));
957 if ( tempname
.empty() )
959 // error, failed to get temp file name
964 fn
->Assign(tempname
);
969 void wxFileName::AssignTempFileName(const wxString
& prefix
)
971 wxAssignTempImpl(this, prefix
, WXFILEARGS(NULL
, NULL
));
975 wxString
wxFileName::CreateTempFileName(const wxString
& prefix
)
977 return wxCreateTempImpl(prefix
, WXFILEARGS(NULL
, NULL
));
980 #endif // wxUSE_FILE || wxUSE_FFILE
985 wxString
wxCreateTempFileName(const wxString
& prefix
,
989 return wxCreateTempImpl(prefix
, WXFILEARGS(fileTemp
, NULL
), deleteOnClose
);
992 bool wxCreateTempFile(const wxString
& prefix
,
996 return wxCreateTempImpl(prefix
, WXFILEARGS(fileTemp
, NULL
), name
);
999 void wxFileName::AssignTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
1001 wxAssignTempImpl(this, prefix
, WXFILEARGS(fileTemp
, NULL
));
1006 wxFileName::CreateTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
1008 return wxCreateTempFileName(prefix
, fileTemp
);
1011 #endif // wxUSE_FILE
1016 wxString
wxCreateTempFileName(const wxString
& prefix
,
1018 bool *deleteOnClose
)
1020 return wxCreateTempImpl(prefix
, WXFILEARGS(NULL
, fileTemp
), deleteOnClose
);
1023 bool wxCreateTempFile(const wxString
& prefix
,
1027 return wxCreateTempImpl(prefix
, WXFILEARGS(NULL
, fileTemp
), name
);
1031 void wxFileName::AssignTempFileName(const wxString
& prefix
, wxFFile
*fileTemp
)
1033 wxAssignTempImpl(this, prefix
, WXFILEARGS(NULL
, fileTemp
));
1038 wxFileName::CreateTempFileName(const wxString
& prefix
, wxFFile
*fileTemp
)
1040 return wxCreateTempFileName(prefix
, fileTemp
);
1043 #endif // wxUSE_FFILE
1046 // ----------------------------------------------------------------------------
1047 // directory operations
1048 // ----------------------------------------------------------------------------
1050 // helper of GetTempDir(): check if the given directory exists and return it if
1051 // it does or an empty string otherwise
1055 wxString
CheckIfDirExists(const wxString
& dir
)
1057 return wxFileName::DirExists(dir
) ? dir
: wxString();
1060 } // anonymous namespace
1062 wxString
wxFileName::GetTempDir()
1064 // first try getting it from environment: this allows overriding the values
1065 // used by default if the user wants to create temporary files in another
1067 wxString dir
= CheckIfDirExists(wxGetenv("TMPDIR"));
1070 dir
= CheckIfDirExists(wxGetenv("TMP"));
1072 dir
= CheckIfDirExists(wxGetenv("TEMP"));
1075 // if no environment variables are set, use the system default
1078 #if defined(__WXWINCE__)
1079 dir
= CheckIfDirExists(wxT("\\temp"));
1080 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1081 if ( !::GetTempPath(MAX_PATH
, wxStringBuffer(dir
, MAX_PATH
+ 1)) )
1083 wxLogLastError(wxT("GetTempPath"));
1085 #elif defined(__WXMAC__) && wxOSX_USE_CARBON
1086 dir
= wxMacFindFolder(short(kOnSystemDisk
), kTemporaryFolderType
, kCreateFolder
);
1087 #endif // systems with native way
1090 // fall back to hard coded value
1093 #ifdef __UNIX_LIKE__
1094 dir
= CheckIfDirExists("/tmp");
1096 #endif // __UNIX_LIKE__
1103 bool wxFileName::Mkdir( int perm
, int flags
) const
1105 return wxFileName::Mkdir(GetPath(), perm
, flags
);
1108 bool wxFileName::Mkdir( const wxString
& dir
, int perm
, int flags
)
1110 if ( flags
& wxPATH_MKDIR_FULL
)
1112 // split the path in components
1113 wxFileName filename
;
1114 filename
.AssignDir(dir
);
1117 if ( filename
.HasVolume())
1119 currPath
<< wxGetVolumeString(filename
.GetVolume(), wxPATH_NATIVE
);
1122 wxArrayString dirs
= filename
.GetDirs();
1123 size_t count
= dirs
.GetCount();
1124 for ( size_t i
= 0; i
< count
; i
++ )
1126 if ( i
> 0 || filename
.IsAbsolute() )
1127 currPath
+= wxFILE_SEP_PATH
;
1128 currPath
+= dirs
[i
];
1130 if (!DirExists(currPath
))
1132 if (!wxMkdir(currPath
, perm
))
1134 // no need to try creating further directories
1144 return ::wxMkdir( dir
, perm
);
1147 bool wxFileName::Rmdir(int flags
) const
1149 return wxFileName::Rmdir( GetPath(), flags
);
1152 bool wxFileName::Rmdir(const wxString
& dir
, int flags
)
1155 if ( flags
& wxPATH_RMDIR_RECURSIVE
)
1157 // SHFileOperation needs double null termination string
1158 // but without separator at the end of the path
1160 if ( path
.Last() == wxFILE_SEP_PATH
)
1164 SHFILEOPSTRUCT fileop
;
1165 wxZeroMemory(fileop
);
1166 fileop
.wFunc
= FO_DELETE
;
1167 fileop
.pFrom
= path
.fn_str();
1168 fileop
.fFlags
= FOF_SILENT
| FOF_NOCONFIRMATION
;
1170 // FOF_NOERRORUI is not defined in WinCE
1171 fileop
.fFlags
|= FOF_NOERRORUI
;
1174 int ret
= SHFileOperation(&fileop
);
1177 // SHFileOperation may return non-Win32 error codes, so the error
1178 // message can be incorrect
1179 wxLogApiError(wxT("SHFileOperation"), ret
);
1185 else if ( flags
& wxPATH_RMDIR_FULL
)
1187 if ( flags
!= 0 ) // wxPATH_RMDIR_FULL or wxPATH_RMDIR_RECURSIVE
1188 #endif // !__WXMSW__
1191 if ( path
.Last() != wxFILE_SEP_PATH
)
1192 path
+= wxFILE_SEP_PATH
;
1196 if ( !d
.IsOpened() )
1201 // first delete all subdirectories
1202 bool cont
= d
.GetFirst(&filename
, "", wxDIR_DIRS
| wxDIR_HIDDEN
);
1205 wxFileName::Rmdir(path
+ filename
, flags
);
1206 cont
= d
.GetNext(&filename
);
1210 if ( flags
& wxPATH_RMDIR_RECURSIVE
)
1212 // delete all files too
1213 cont
= d
.GetFirst(&filename
, "", wxDIR_FILES
| wxDIR_HIDDEN
);
1216 ::wxRemoveFile(path
+ filename
);
1217 cont
= d
.GetNext(&filename
);
1220 #endif // !__WXMSW__
1223 return ::wxRmdir(dir
);
1226 // ----------------------------------------------------------------------------
1227 // path normalization
1228 // ----------------------------------------------------------------------------
1230 bool wxFileName::Normalize(int flags
,
1231 const wxString
& cwd
,
1232 wxPathFormat format
)
1234 // deal with env vars renaming first as this may seriously change the path
1235 if ( flags
& wxPATH_NORM_ENV_VARS
)
1237 wxString pathOrig
= GetFullPath(format
);
1238 wxString path
= wxExpandEnvVars(pathOrig
);
1239 if ( path
!= pathOrig
)
1245 // the existing path components
1246 wxArrayString dirs
= GetDirs();
1248 // the path to prepend in front to make the path absolute
1251 format
= GetFormat(format
);
1253 // set up the directory to use for making the path absolute later
1254 if ( (flags
& wxPATH_NORM_ABSOLUTE
) && !IsAbsolute(format
) )
1258 curDir
.AssignCwd(GetVolume());
1260 else // cwd provided
1262 curDir
.AssignDir(cwd
);
1266 // handle ~ stuff under Unix only
1267 if ( (format
== wxPATH_UNIX
) && (flags
& wxPATH_NORM_TILDE
) && m_relative
)
1269 if ( !dirs
.IsEmpty() )
1271 wxString dir
= dirs
[0u];
1272 if ( !dir
.empty() && dir
[0u] == wxT('~') )
1274 // to make the path absolute use the home directory
1275 curDir
.AssignDir(wxGetUserHome(dir
.c_str() + 1));
1281 // transform relative path into abs one
1282 if ( curDir
.IsOk() )
1284 // this path may be relative because it doesn't have the volume name
1285 // and still have m_relative=true; in this case we shouldn't modify
1286 // our directory components but just set the current volume
1287 if ( !HasVolume() && curDir
.HasVolume() )
1289 SetVolume(curDir
.GetVolume());
1293 // yes, it was the case - we don't need curDir then
1298 // finally, prepend curDir to the dirs array
1299 wxArrayString dirsNew
= curDir
.GetDirs();
1300 WX_PREPEND_ARRAY(dirs
, dirsNew
);
1302 // if we used e.g. tilde expansion previously and wxGetUserHome didn't
1303 // return for some reason an absolute path, then curDir maybe not be absolute!
1304 if ( !curDir
.m_relative
)
1306 // we have prepended an absolute path and thus we are now an absolute
1310 // else if (flags & wxPATH_NORM_ABSOLUTE):
1311 // should we warn the user that we didn't manage to make the path absolute?
1314 // now deal with ".", ".." and the rest
1316 size_t count
= dirs
.GetCount();
1317 for ( size_t n
= 0; n
< count
; n
++ )
1319 wxString dir
= dirs
[n
];
1321 if ( flags
& wxPATH_NORM_DOTS
)
1323 if ( dir
== wxT(".") )
1329 if ( dir
== wxT("..") )
1331 if ( m_dirs
.IsEmpty() )
1333 wxLogError(_("The path '%s' contains too many \"..\"!"),
1334 GetFullPath().c_str());
1338 m_dirs
.RemoveAt(m_dirs
.GetCount() - 1);
1346 #if defined(__WIN32__) && !defined(__WXWINCE__) && wxUSE_OLE
1347 if ( (flags
& wxPATH_NORM_SHORTCUT
) )
1350 if (GetShortcutTarget(GetFullPath(format
), filename
))
1358 #if defined(__WIN32__)
1359 if ( (flags
& wxPATH_NORM_LONG
) && (format
== wxPATH_DOS
) )
1361 Assign(GetLongPath());
1365 // Change case (this should be kept at the end of the function, to ensure
1366 // that the path doesn't change any more after we normalize its case)
1367 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
1369 m_volume
.MakeLower();
1373 // directory entries must be made lower case as well
1374 count
= m_dirs
.GetCount();
1375 for ( size_t i
= 0; i
< count
; i
++ )
1377 m_dirs
[i
].MakeLower();
1385 bool wxFileName::ReplaceEnvVariable(const wxString
& envname
,
1386 const wxString
& replacementFmtString
,
1387 wxPathFormat format
)
1389 // look into stringForm for the contents of the given environment variable
1391 if (envname
.empty() ||
1392 !wxGetEnv(envname
, &val
))
1397 wxString stringForm
= GetPath(wxPATH_GET_VOLUME
, format
);
1398 // do not touch the file name and the extension
1400 wxString replacement
= wxString::Format(replacementFmtString
, envname
);
1401 stringForm
.Replace(val
, replacement
);
1403 // Now assign ourselves the modified path:
1404 Assign(stringForm
, GetFullName(), format
);
1410 bool wxFileName::ReplaceHomeDir(wxPathFormat format
)
1412 wxString homedir
= wxGetHomeDir();
1413 if (homedir
.empty())
1416 wxString stringForm
= GetPath(wxPATH_GET_VOLUME
, format
);
1417 // do not touch the file name and the extension
1419 stringForm
.Replace(homedir
, "~");
1421 // Now assign ourselves the modified path:
1422 Assign(stringForm
, GetFullName(), format
);
1427 // ----------------------------------------------------------------------------
1428 // get the shortcut target
1429 // ----------------------------------------------------------------------------
1431 // WinCE (3) doesn't have CLSID_ShellLink, IID_IShellLink definitions.
1432 // The .lnk file is a plain text file so it should be easy to
1433 // make it work. Hint from Google Groups:
1434 // "If you open up a lnk file, you'll see a
1435 // number, followed by a pound sign (#), followed by more text. The
1436 // number is the number of characters that follows the pound sign. The
1437 // characters after the pound sign are the command line (which _can_
1438 // include arguments) to be executed. Any path (e.g. \windows\program
1439 // files\myapp.exe) that includes spaces needs to be enclosed in
1440 // quotation marks."
1442 #if defined(__WIN32__) && !defined(__WXWINCE__) && wxUSE_OLE
1443 // The following lines are necessary under WinCE
1444 // #include "wx/msw/private.h"
1445 // #include <ole2.h>
1447 #if defined(__WXWINCE__)
1448 #include <shlguid.h>
1451 bool wxFileName::GetShortcutTarget(const wxString
& shortcutPath
,
1452 wxString
& targetFilename
,
1453 wxString
* arguments
) const
1455 wxString path
, file
, ext
;
1456 wxFileName::SplitPath(shortcutPath
, & path
, & file
, & ext
);
1460 bool success
= false;
1462 // Assume it's not a shortcut if it doesn't end with lnk
1463 if (ext
.CmpNoCase(wxT("lnk"))!=0)
1466 // create a ShellLink object
1467 hres
= CoCreateInstance(CLSID_ShellLink
, NULL
, CLSCTX_INPROC_SERVER
,
1468 IID_IShellLink
, (LPVOID
*) &psl
);
1470 if (SUCCEEDED(hres
))
1473 hres
= psl
->QueryInterface( IID_IPersistFile
, (LPVOID
*) &ppf
);
1474 if (SUCCEEDED(hres
))
1476 WCHAR wsz
[MAX_PATH
];
1478 MultiByteToWideChar(CP_ACP
, MB_PRECOMPOSED
, shortcutPath
.mb_str(), -1, wsz
,
1481 hres
= ppf
->Load(wsz
, 0);
1484 if (SUCCEEDED(hres
))
1487 // Wrong prototype in early versions
1488 #if defined(__MINGW32__) && !wxCHECK_W32API_VERSION(2, 2)
1489 psl
->GetPath((CHAR
*) buf
, 2048, NULL
, SLGP_UNCPRIORITY
);
1491 psl
->GetPath(buf
, 2048, NULL
, SLGP_UNCPRIORITY
);
1493 targetFilename
= wxString(buf
);
1494 success
= (shortcutPath
!= targetFilename
);
1496 psl
->GetArguments(buf
, 2048);
1498 if (!args
.empty() && arguments
)
1510 #endif // __WIN32__ && !__WXWINCE__
1513 // ----------------------------------------------------------------------------
1514 // absolute/relative paths
1515 // ----------------------------------------------------------------------------
1517 bool wxFileName::IsAbsolute(wxPathFormat format
) const
1519 // unix paths beginning with ~ are reported as being absolute
1520 if ( format
== wxPATH_UNIX
)
1522 if ( !m_dirs
.IsEmpty() )
1524 wxString dir
= m_dirs
[0u];
1526 if (!dir
.empty() && dir
[0u] == wxT('~'))
1531 // if our path doesn't start with a path separator, it's not an absolute
1536 if ( !GetVolumeSeparator(format
).empty() )
1538 // this format has volumes and an absolute path must have one, it's not
1539 // enough to have the full path to be an absolute file under Windows
1540 if ( GetVolume().empty() )
1547 bool wxFileName::MakeRelativeTo(const wxString
& pathBase
, wxPathFormat format
)
1549 wxFileName fnBase
= wxFileName::DirName(pathBase
, format
);
1551 // get cwd only once - small time saving
1552 wxString cwd
= wxGetCwd();
1553 Normalize(wxPATH_NORM_ALL
& ~wxPATH_NORM_CASE
, cwd
, format
);
1554 fnBase
.Normalize(wxPATH_NORM_ALL
& ~wxPATH_NORM_CASE
, cwd
, format
);
1556 bool withCase
= IsCaseSensitive(format
);
1558 // we can't do anything if the files live on different volumes
1559 if ( !GetVolume().IsSameAs(fnBase
.GetVolume(), withCase
) )
1565 // same drive, so we don't need our volume
1568 // remove common directories starting at the top
1569 while ( !m_dirs
.IsEmpty() && !fnBase
.m_dirs
.IsEmpty() &&
1570 m_dirs
[0u].IsSameAs(fnBase
.m_dirs
[0u], withCase
) )
1573 fnBase
.m_dirs
.RemoveAt(0);
1576 // add as many ".." as needed
1577 size_t count
= fnBase
.m_dirs
.GetCount();
1578 for ( size_t i
= 0; i
< count
; i
++ )
1580 m_dirs
.Insert(wxT(".."), 0u);
1583 if ( format
== wxPATH_UNIX
|| format
== wxPATH_DOS
)
1585 // a directory made relative with respect to itself is '.' under Unix
1586 // and DOS, by definition (but we don't have to insert "./" for the
1588 if ( m_dirs
.IsEmpty() && IsDir() )
1590 m_dirs
.Add(wxT('.'));
1600 // ----------------------------------------------------------------------------
1601 // filename kind tests
1602 // ----------------------------------------------------------------------------
1604 bool wxFileName::SameAs(const wxFileName
& filepath
, wxPathFormat format
) const
1606 wxFileName fn1
= *this,
1609 // get cwd only once - small time saving
1610 wxString cwd
= wxGetCwd();
1611 fn1
.Normalize(wxPATH_NORM_ALL
| wxPATH_NORM_CASE
, cwd
, format
);
1612 fn2
.Normalize(wxPATH_NORM_ALL
| wxPATH_NORM_CASE
, cwd
, format
);
1614 if ( fn1
.GetFullPath() == fn2
.GetFullPath() )
1617 // TODO: compare inodes for Unix, this works even when filenames are
1618 // different but files are the same (symlinks) (VZ)
1624 bool wxFileName::IsCaseSensitive( wxPathFormat format
)
1626 // only Unix filenames are truely case-sensitive
1627 return GetFormat(format
) == wxPATH_UNIX
;
1631 wxString
wxFileName::GetForbiddenChars(wxPathFormat format
)
1633 // Inits to forbidden characters that are common to (almost) all platforms.
1634 wxString strForbiddenChars
= wxT("*?");
1636 // If asserts, wxPathFormat has been changed. In case of a new path format
1637 // addition, the following code might have to be updated.
1638 wxCOMPILE_TIME_ASSERT(wxPATH_MAX
== 5, wxPathFormatChanged
);
1639 switch ( GetFormat(format
) )
1642 wxFAIL_MSG( wxT("Unknown path format") );
1643 // !! Fall through !!
1649 // On a Mac even names with * and ? are allowed (Tested with OS
1650 // 9.2.1 and OS X 10.2.5)
1651 strForbiddenChars
= wxEmptyString
;
1655 strForbiddenChars
+= wxT("\\/:\"<>|");
1662 return strForbiddenChars
;
1666 wxString
wxFileName::GetVolumeSeparator(wxPathFormat
WXUNUSED_IN_WINCE(format
))
1669 return wxEmptyString
;
1673 if ( (GetFormat(format
) == wxPATH_DOS
) ||
1674 (GetFormat(format
) == wxPATH_VMS
) )
1676 sepVol
= wxFILE_SEP_DSK
;
1685 wxString
wxFileName::GetPathSeparators(wxPathFormat format
)
1688 switch ( GetFormat(format
) )
1691 // accept both as native APIs do but put the native one first as
1692 // this is the one we use in GetFullPath()
1693 seps
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_UNIX
;
1697 wxFAIL_MSG( wxT("Unknown wxPATH_XXX style") );
1701 seps
= wxFILE_SEP_PATH_UNIX
;
1705 seps
= wxFILE_SEP_PATH_MAC
;
1709 seps
= wxFILE_SEP_PATH_VMS
;
1717 wxString
wxFileName::GetPathTerminators(wxPathFormat format
)
1719 format
= GetFormat(format
);
1721 // under VMS the end of the path is ']', not the path separator used to
1722 // separate the components
1723 return format
== wxPATH_VMS
? wxString(wxT(']')) : GetPathSeparators(format
);
1727 bool wxFileName::IsPathSeparator(wxChar ch
, wxPathFormat format
)
1729 // wxString::Find() doesn't work as expected with NUL - it will always find
1730 // it, so test for it separately
1731 return ch
!= wxT('\0') && GetPathSeparators(format
).Find(ch
) != wxNOT_FOUND
;
1734 // ----------------------------------------------------------------------------
1735 // path components manipulation
1736 // ----------------------------------------------------------------------------
1738 /* static */ bool wxFileName::IsValidDirComponent(const wxString
& dir
)
1742 wxFAIL_MSG( wxT("empty directory passed to wxFileName::InsertDir()") );
1747 const size_t len
= dir
.length();
1748 for ( size_t n
= 0; n
< len
; n
++ )
1750 if ( dir
[n
] == GetVolumeSeparator() || IsPathSeparator(dir
[n
]) )
1752 wxFAIL_MSG( wxT("invalid directory component in wxFileName") );
1761 void wxFileName::AppendDir( const wxString
& dir
)
1763 if ( IsValidDirComponent(dir
) )
1767 void wxFileName::PrependDir( const wxString
& dir
)
1772 void wxFileName::InsertDir(size_t before
, const wxString
& dir
)
1774 if ( IsValidDirComponent(dir
) )
1775 m_dirs
.Insert(dir
, before
);
1778 void wxFileName::RemoveDir(size_t pos
)
1780 m_dirs
.RemoveAt(pos
);
1783 // ----------------------------------------------------------------------------
1785 // ----------------------------------------------------------------------------
1787 void wxFileName::SetFullName(const wxString
& fullname
)
1789 SplitPath(fullname
, NULL
/* no volume */, NULL
/* no path */,
1790 &m_name
, &m_ext
, &m_hasExt
);
1793 wxString
wxFileName::GetFullName() const
1795 wxString fullname
= m_name
;
1798 fullname
<< wxFILE_SEP_EXT
<< m_ext
;
1804 wxString
wxFileName::GetPath( int flags
, wxPathFormat format
) const
1806 format
= GetFormat( format
);
1810 // return the volume with the path as well if requested
1811 if ( flags
& wxPATH_GET_VOLUME
)
1813 fullpath
+= wxGetVolumeString(GetVolume(), format
);
1816 // the leading character
1821 fullpath
+= wxFILE_SEP_PATH_MAC
;
1826 fullpath
+= wxFILE_SEP_PATH_DOS
;
1830 wxFAIL_MSG( wxT("Unknown path format") );
1836 fullpath
+= wxFILE_SEP_PATH_UNIX
;
1841 // no leading character here but use this place to unset
1842 // wxPATH_GET_SEPARATOR flag: under VMS it doesn't make sense
1843 // as, if I understand correctly, there should never be a dot
1844 // before the closing bracket
1845 flags
&= ~wxPATH_GET_SEPARATOR
;
1848 if ( m_dirs
.empty() )
1850 // there is nothing more
1854 // then concatenate all the path components using the path separator
1855 if ( format
== wxPATH_VMS
)
1857 fullpath
+= wxT('[');
1860 const size_t dirCount
= m_dirs
.GetCount();
1861 for ( size_t i
= 0; i
< dirCount
; i
++ )
1866 if ( m_dirs
[i
] == wxT(".") )
1868 // skip appending ':', this shouldn't be done in this
1869 // case as "::" is interpreted as ".." under Unix
1873 // convert back from ".." to nothing
1874 if ( !m_dirs
[i
].IsSameAs(wxT("..")) )
1875 fullpath
+= m_dirs
[i
];
1879 wxFAIL_MSG( wxT("Unexpected path format") );
1880 // still fall through
1884 fullpath
+= m_dirs
[i
];
1888 // TODO: What to do with ".." under VMS
1890 // convert back from ".." to nothing
1891 if ( !m_dirs
[i
].IsSameAs(wxT("..")) )
1892 fullpath
+= m_dirs
[i
];
1896 if ( (flags
& wxPATH_GET_SEPARATOR
) || (i
!= dirCount
- 1) )
1897 fullpath
+= GetPathSeparator(format
);
1900 if ( format
== wxPATH_VMS
)
1902 fullpath
+= wxT(']');
1908 wxString
wxFileName::GetFullPath( wxPathFormat format
) const
1910 // we already have a function to get the path
1911 wxString fullpath
= GetPath(wxPATH_GET_VOLUME
| wxPATH_GET_SEPARATOR
,
1914 // now just add the file name and extension to it
1915 fullpath
+= GetFullName();
1920 // Return the short form of the path (returns identity on non-Windows platforms)
1921 wxString
wxFileName::GetShortPath() const
1923 wxString
path(GetFullPath());
1925 #if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
1926 DWORD sz
= ::GetShortPathName(path
.fn_str(), NULL
, 0);
1930 if ( ::GetShortPathName
1933 wxStringBuffer(pathOut
, sz
),
1945 // Return the long form of the path (returns identity on non-Windows platforms)
1946 wxString
wxFileName::GetLongPath() const
1949 path
= GetFullPath();
1951 #if defined(__WIN32__) && !defined(__WXWINCE__) && !defined(__WXMICROWIN__)
1953 #if wxUSE_DYNLIB_CLASS
1954 typedef DWORD (WINAPI
*GET_LONG_PATH_NAME
)(const wxChar
*, wxChar
*, DWORD
);
1956 // this is MT-safe as in the worst case we're going to resolve the function
1957 // twice -- but as the result is the same in both threads, it's ok
1958 static GET_LONG_PATH_NAME s_pfnGetLongPathName
= NULL
;
1959 if ( !s_pfnGetLongPathName
)
1961 static bool s_triedToLoad
= false;
1963 if ( !s_triedToLoad
)
1965 s_triedToLoad
= true;
1967 wxDynamicLibrary
dllKernel(wxT("kernel32"));
1969 const wxChar
* GetLongPathName
= wxT("GetLongPathName")
1974 #endif // Unicode/ANSI
1976 if ( dllKernel
.HasSymbol(GetLongPathName
) )
1978 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
)
1979 dllKernel
.GetSymbol(GetLongPathName
);
1982 // note that kernel32.dll can be unloaded, it stays in memory
1983 // anyhow as all Win32 programs link to it and so it's safe to call
1984 // GetLongPathName() even after unloading it
1988 if ( s_pfnGetLongPathName
)
1990 DWORD dwSize
= (*s_pfnGetLongPathName
)(path
.fn_str(), NULL
, 0);
1993 if ( (*s_pfnGetLongPathName
)
1996 wxStringBuffer(pathOut
, dwSize
),
2004 #endif // wxUSE_DYNLIB_CLASS
2006 // The OS didn't support GetLongPathName, or some other error.
2007 // We need to call FindFirstFile on each component in turn.
2009 WIN32_FIND_DATA findFileData
;
2013 pathOut
= GetVolume() +
2014 GetVolumeSeparator(wxPATH_DOS
) +
2015 GetPathSeparator(wxPATH_DOS
);
2017 pathOut
= wxEmptyString
;
2019 wxArrayString dirs
= GetDirs();
2020 dirs
.Add(GetFullName());
2024 size_t count
= dirs
.GetCount();
2025 for ( size_t i
= 0; i
< count
; i
++ )
2027 const wxString
& dir
= dirs
[i
];
2029 // We're using pathOut to collect the long-name path, but using a
2030 // temporary for appending the last path component which may be
2032 tmpPath
= pathOut
+ dir
;
2034 // We must not process "." or ".." here as they would be (unexpectedly)
2035 // replaced by the corresponding directory names so just leave them
2038 // And we can't pass a drive and root dir to FindFirstFile (VZ: why?)
2039 if ( tmpPath
.empty() || dir
== '.' || dir
== ".." ||
2040 tmpPath
.Last() == GetVolumeSeparator(wxPATH_DOS
) )
2042 tmpPath
+= wxFILE_SEP_PATH
;
2047 hFind
= ::FindFirstFile(tmpPath
.fn_str(), &findFileData
);
2048 if (hFind
== INVALID_HANDLE_VALUE
)
2050 // Error: most likely reason is that path doesn't exist, so
2051 // append any unprocessed parts and return
2052 for ( i
+= 1; i
< count
; i
++ )
2053 tmpPath
+= wxFILE_SEP_PATH
+ dirs
[i
];
2058 pathOut
+= findFileData
.cFileName
;
2059 if ( (i
< (count
-1)) )
2060 pathOut
+= wxFILE_SEP_PATH
;
2066 #endif // Win32/!Win32
2071 wxPathFormat
wxFileName::GetFormat( wxPathFormat format
)
2073 if (format
== wxPATH_NATIVE
)
2075 #if defined(__WXMSW__) || defined(__OS2__) || defined(__DOS__)
2076 format
= wxPATH_DOS
;
2077 #elif defined(__VMS)
2078 format
= wxPATH_VMS
;
2080 format
= wxPATH_UNIX
;
2086 #ifdef wxHAS_FILESYSTEM_VOLUMES
2089 wxString
wxFileName::GetVolumeString(char drive
, int flags
)
2091 wxASSERT_MSG( !(flags
& ~wxPATH_GET_SEPARATOR
), "invalid flag specified" );
2093 wxString
vol(drive
);
2094 vol
+= wxFILE_SEP_DSK
;
2095 if ( flags
& wxPATH_GET_SEPARATOR
)
2096 vol
+= wxFILE_SEP_PATH
;
2101 #endif // wxHAS_FILESYSTEM_VOLUMES
2103 // ----------------------------------------------------------------------------
2104 // path splitting function
2105 // ----------------------------------------------------------------------------
2109 wxFileName::SplitVolume(const wxString
& fullpathWithVolume
,
2110 wxString
*pstrVolume
,
2112 wxPathFormat format
)
2114 format
= GetFormat(format
);
2116 wxString fullpath
= fullpathWithVolume
;
2118 // special Windows UNC paths hack: transform \\share\path into share:path
2119 if ( IsUNCPath(fullpath
, format
) )
2121 fullpath
.erase(0, 2);
2123 size_t posFirstSlash
=
2124 fullpath
.find_first_of(GetPathTerminators(format
));
2125 if ( posFirstSlash
!= wxString::npos
)
2127 fullpath
[posFirstSlash
] = wxFILE_SEP_DSK
;
2129 // UNC paths are always absolute, right? (FIXME)
2130 fullpath
.insert(posFirstSlash
+ 1, 1, wxFILE_SEP_PATH_DOS
);
2134 // We separate the volume here
2135 if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
2137 wxString sepVol
= GetVolumeSeparator(format
);
2139 // we have to exclude the case of a colon in the very beginning of the
2140 // string as it can't be a volume separator (nor can this be a valid
2141 // DOS file name at all but we'll leave dealing with this to our caller)
2142 size_t posFirstColon
= fullpath
.find_first_of(sepVol
);
2143 if ( posFirstColon
&& posFirstColon
!= wxString::npos
)
2147 *pstrVolume
= fullpath
.Left(posFirstColon
);
2150 // remove the volume name and the separator from the full path
2151 fullpath
.erase(0, posFirstColon
+ sepVol
.length());
2156 *pstrPath
= fullpath
;
2160 void wxFileName::SplitPath(const wxString
& fullpathWithVolume
,
2161 wxString
*pstrVolume
,
2166 wxPathFormat format
)
2168 format
= GetFormat(format
);
2171 SplitVolume(fullpathWithVolume
, pstrVolume
, &fullpath
, format
);
2173 // find the positions of the last dot and last path separator in the path
2174 size_t posLastDot
= fullpath
.find_last_of(wxFILE_SEP_EXT
);
2175 size_t posLastSlash
= fullpath
.find_last_of(GetPathTerminators(format
));
2177 // check whether this dot occurs at the very beginning of a path component
2178 if ( (posLastDot
!= wxString::npos
) &&
2180 IsPathSeparator(fullpath
[posLastDot
- 1]) ||
2181 (format
== wxPATH_VMS
&& fullpath
[posLastDot
- 1] == wxT(']'))) )
2183 // dot may be (and commonly -- at least under Unix -- is) the first
2184 // character of the filename, don't treat the entire filename as
2185 // extension in this case
2186 posLastDot
= wxString::npos
;
2189 // if we do have a dot and a slash, check that the dot is in the name part
2190 if ( (posLastDot
!= wxString::npos
) &&
2191 (posLastSlash
!= wxString::npos
) &&
2192 (posLastDot
< posLastSlash
) )
2194 // the dot is part of the path, not the start of the extension
2195 posLastDot
= wxString::npos
;
2198 // now fill in the variables provided by user
2201 if ( posLastSlash
== wxString::npos
)
2208 // take everything up to the path separator but take care to make
2209 // the path equal to something like '/', not empty, for the files
2210 // immediately under root directory
2211 size_t len
= posLastSlash
;
2213 // this rule does not apply to mac since we do not start with colons (sep)
2214 // except for relative paths
2215 if ( !len
&& format
!= wxPATH_MAC
)
2218 *pstrPath
= fullpath
.Left(len
);
2220 // special VMS hack: remove the initial bracket
2221 if ( format
== wxPATH_VMS
)
2223 if ( (*pstrPath
)[0u] == wxT('[') )
2224 pstrPath
->erase(0, 1);
2231 // take all characters starting from the one after the last slash and
2232 // up to, but excluding, the last dot
2233 size_t nStart
= posLastSlash
== wxString::npos
? 0 : posLastSlash
+ 1;
2235 if ( posLastDot
== wxString::npos
)
2237 // take all until the end
2238 count
= wxString::npos
;
2240 else if ( posLastSlash
== wxString::npos
)
2244 else // have both dot and slash
2246 count
= posLastDot
- posLastSlash
- 1;
2249 *pstrName
= fullpath
.Mid(nStart
, count
);
2252 // finally deal with the extension here: we have an added complication that
2253 // extension may be empty (but present) as in "foo." where trailing dot
2254 // indicates the empty extension at the end -- and hence we must remember
2255 // that we have it independently of pstrExt
2256 if ( posLastDot
== wxString::npos
)
2266 // take everything after the dot
2268 *pstrExt
= fullpath
.Mid(posLastDot
+ 1);
2275 void wxFileName::SplitPath(const wxString
& fullpath
,
2279 wxPathFormat format
)
2282 SplitPath(fullpath
, &volume
, path
, name
, ext
, format
);
2286 path
->Prepend(wxGetVolumeString(volume
, format
));
2291 wxString
wxFileName::StripExtension(const wxString
& fullpath
)
2293 wxFileName
fn(fullpath
);
2295 return fn
.GetFullPath();
2298 // ----------------------------------------------------------------------------
2300 // ----------------------------------------------------------------------------
2304 bool wxFileName::SetTimes(const wxDateTime
*dtAccess
,
2305 const wxDateTime
*dtMod
,
2306 const wxDateTime
*dtCreate
) const
2308 #if defined(__WIN32__)
2309 FILETIME ftAccess
, ftCreate
, ftWrite
;
2312 ConvertWxToFileTime(&ftCreate
, *dtCreate
);
2314 ConvertWxToFileTime(&ftAccess
, *dtAccess
);
2316 ConvertWxToFileTime(&ftWrite
, *dtMod
);
2322 if ( wxGetOsVersion() == wxOS_WINDOWS_9X
)
2324 wxLogError(_("Setting directory access times is not supported "
2325 "under this OS version"));
2330 flags
= FILE_FLAG_BACKUP_SEMANTICS
;
2334 path
= GetFullPath();
2338 wxFileHandle
fh(path
, wxFileHandle::WriteAttr
, flags
);
2341 if ( ::SetFileTime(fh
,
2342 dtCreate
? &ftCreate
: NULL
,
2343 dtAccess
? &ftAccess
: NULL
,
2344 dtMod
? &ftWrite
: NULL
) )
2349 #elif defined(__UNIX_LIKE__) || (defined(__DOS__) && defined(__WATCOMC__))
2350 wxUnusedVar(dtCreate
);
2352 if ( !dtAccess
&& !dtMod
)
2354 // can't modify the creation time anyhow, don't try
2358 // if dtAccess or dtMod is not specified, use the other one (which must be
2359 // non NULL because of the test above) for both times
2361 utm
.actime
= dtAccess
? dtAccess
->GetTicks() : dtMod
->GetTicks();
2362 utm
.modtime
= dtMod
? dtMod
->GetTicks() : dtAccess
->GetTicks();
2363 if ( utime(GetFullPath().fn_str(), &utm
) == 0 )
2367 #else // other platform
2368 wxUnusedVar(dtAccess
);
2370 wxUnusedVar(dtCreate
);
2373 wxLogSysError(_("Failed to modify file times for '%s'"),
2374 GetFullPath().c_str());
2379 bool wxFileName::Touch() const
2381 #if defined(__UNIX_LIKE__)
2382 // under Unix touching file is simple: just pass NULL to utime()
2383 if ( utime(GetFullPath().fn_str(), NULL
) == 0 )
2388 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
2391 #else // other platform
2392 wxDateTime dtNow
= wxDateTime::Now();
2394 return SetTimes(&dtNow
, &dtNow
, NULL
/* don't change create time */);
2398 bool wxFileName::GetTimes(wxDateTime
*dtAccess
,
2400 wxDateTime
*dtCreate
) const
2402 #if defined(__WIN32__)
2403 // we must use different methods for the files and directories under
2404 // Windows as CreateFile(GENERIC_READ) doesn't work for the directories and
2405 // CreateFile(FILE_FLAG_BACKUP_SEMANTICS) works -- but only under NT and
2408 FILETIME ftAccess
, ftCreate
, ftWrite
;
2411 // implemented in msw/dir.cpp
2412 extern bool wxGetDirectoryTimes(const wxString
& dirname
,
2413 FILETIME
*, FILETIME
*, FILETIME
*);
2415 // we should pass the path without the trailing separator to
2416 // wxGetDirectoryTimes()
2417 ok
= wxGetDirectoryTimes(GetPath(wxPATH_GET_VOLUME
),
2418 &ftAccess
, &ftCreate
, &ftWrite
);
2422 wxFileHandle
fh(GetFullPath(), wxFileHandle::ReadAttr
);
2425 ok
= ::GetFileTime(fh
,
2426 dtCreate
? &ftCreate
: NULL
,
2427 dtAccess
? &ftAccess
: NULL
,
2428 dtMod
? &ftWrite
: NULL
) != 0;
2439 ConvertFileTimeToWx(dtCreate
, ftCreate
);
2441 ConvertFileTimeToWx(dtAccess
, ftAccess
);
2443 ConvertFileTimeToWx(dtMod
, ftWrite
);
2447 #elif defined(__UNIX_LIKE__) || defined(__WXMAC__) || defined(__OS2__) || (defined(__DOS__) && defined(__WATCOMC__))
2448 // no need to test for IsDir() here
2450 if ( wxStat( GetFullPath().c_str(), &stBuf
) == 0 )
2453 dtAccess
->Set(stBuf
.st_atime
);
2455 dtMod
->Set(stBuf
.st_mtime
);
2457 dtCreate
->Set(stBuf
.st_ctime
);
2461 #else // other platform
2462 wxUnusedVar(dtAccess
);
2464 wxUnusedVar(dtCreate
);
2467 wxLogSysError(_("Failed to retrieve file times for '%s'"),
2468 GetFullPath().c_str());
2473 #endif // wxUSE_DATETIME
2476 // ----------------------------------------------------------------------------
2477 // file size functions
2478 // ----------------------------------------------------------------------------
2483 wxULongLong
wxFileName::GetSize(const wxString
&filename
)
2485 if (!wxFileExists(filename
))
2486 return wxInvalidSize
;
2488 #if defined(__WXPALMOS__)
2490 return wxInvalidSize
;
2491 #elif defined(__WIN32__)
2492 wxFileHandle
f(filename
, wxFileHandle::ReadAttr
);
2494 return wxInvalidSize
;
2496 DWORD lpFileSizeHigh
;
2497 DWORD ret
= GetFileSize(f
, &lpFileSizeHigh
);
2498 if ( ret
== INVALID_FILE_SIZE
&& ::GetLastError() != NO_ERROR
)
2499 return wxInvalidSize
;
2501 return wxULongLong(lpFileSizeHigh
, ret
);
2502 #else // ! __WIN32__
2504 #ifndef wxNEED_WX_UNISTD_H
2505 if (wxStat( filename
.fn_str() , &st
) != 0)
2507 if (wxStat( filename
, &st
) != 0)
2509 return wxInvalidSize
;
2510 return wxULongLong(st
.st_size
);
2515 wxString
wxFileName::GetHumanReadableSize(const wxULongLong
&bs
,
2516 const wxString
&nullsize
,
2519 static const double KILOBYTESIZE
= 1024.0;
2520 static const double MEGABYTESIZE
= 1024.0*KILOBYTESIZE
;
2521 static const double GIGABYTESIZE
= 1024.0*MEGABYTESIZE
;
2522 static const double TERABYTESIZE
= 1024.0*GIGABYTESIZE
;
2524 if (bs
== 0 || bs
== wxInvalidSize
)
2527 double bytesize
= bs
.ToDouble();
2528 if (bytesize
< KILOBYTESIZE
)
2529 return wxString::Format(_("%s B"), bs
.ToString().c_str());
2530 if (bytesize
< MEGABYTESIZE
)
2531 return wxString::Format(_("%.*f kB"), precision
, bytesize
/KILOBYTESIZE
);
2532 if (bytesize
< GIGABYTESIZE
)
2533 return wxString::Format(_("%.*f MB"), precision
, bytesize
/MEGABYTESIZE
);
2534 if (bytesize
< TERABYTESIZE
)
2535 return wxString::Format(_("%.*f GB"), precision
, bytesize
/GIGABYTESIZE
);
2537 return wxString::Format(_("%.*f TB"), precision
, bytesize
/TERABYTESIZE
);
2540 wxULongLong
wxFileName::GetSize() const
2542 return GetSize(GetFullPath());
2545 wxString
wxFileName::GetHumanReadableSize(const wxString
&failmsg
, int precision
) const
2547 return GetHumanReadableSize(GetSize(), failmsg
, precision
);
2550 #endif // wxUSE_LONGLONG
2552 // ----------------------------------------------------------------------------
2553 // Mac-specific functions
2554 // ----------------------------------------------------------------------------
2556 #if defined( __WXOSX_MAC__ ) && wxOSX_USE_CARBON
2561 class MacDefaultExtensionRecord
2564 MacDefaultExtensionRecord()
2570 // default copy ctor, assignment operator and dtor are ok
2572 MacDefaultExtensionRecord(const wxString
& ext
, OSType type
, OSType creator
)
2576 m_creator
= creator
;
2584 WX_DECLARE_OBJARRAY(MacDefaultExtensionRecord
, MacDefaultExtensionArray
);
2586 bool gMacDefaultExtensionsInited
= false;
2588 #include "wx/arrimpl.cpp"
2590 WX_DEFINE_EXPORTED_OBJARRAY(MacDefaultExtensionArray
);
2592 MacDefaultExtensionArray gMacDefaultExtensions
;
2594 // load the default extensions
2595 const MacDefaultExtensionRecord gDefaults
[] =
2597 MacDefaultExtensionRecord( "txt", 'TEXT', 'ttxt' ),
2598 MacDefaultExtensionRecord( "tif", 'TIFF', '****' ),
2599 MacDefaultExtensionRecord( "jpg", 'JPEG', '****' ),
2602 void MacEnsureDefaultExtensionsLoaded()
2604 if ( !gMacDefaultExtensionsInited
)
2606 // we could load the pc exchange prefs here too
2607 for ( size_t i
= 0 ; i
< WXSIZEOF( gDefaults
) ; ++i
)
2609 gMacDefaultExtensions
.Add( gDefaults
[i
] ) ;
2611 gMacDefaultExtensionsInited
= true;
2615 } // anonymous namespace
2617 bool wxFileName::MacSetTypeAndCreator( wxUint32 type
, wxUint32 creator
)
2620 FSCatalogInfo catInfo
;
2623 if ( wxMacPathToFSRef( GetFullPath() , &fsRef
) == noErr
)
2625 if ( FSGetCatalogInfo (&fsRef
, kFSCatInfoFinderInfo
, &catInfo
, NULL
, NULL
, NULL
) == noErr
)
2627 finfo
= (FileInfo
*)&catInfo
.finderInfo
;
2628 finfo
->fileType
= type
;
2629 finfo
->fileCreator
= creator
;
2630 FSSetCatalogInfo( &fsRef
, kFSCatInfoFinderInfo
, &catInfo
) ;
2637 bool wxFileName::MacGetTypeAndCreator( wxUint32
*type
, wxUint32
*creator
) const
2640 FSCatalogInfo catInfo
;
2643 if ( wxMacPathToFSRef( GetFullPath() , &fsRef
) == noErr
)
2645 if ( FSGetCatalogInfo (&fsRef
, kFSCatInfoFinderInfo
, &catInfo
, NULL
, NULL
, NULL
) == noErr
)
2647 finfo
= (FileInfo
*)&catInfo
.finderInfo
;
2648 *type
= finfo
->fileType
;
2649 *creator
= finfo
->fileCreator
;
2656 bool wxFileName::MacSetDefaultTypeAndCreator()
2658 wxUint32 type
, creator
;
2659 if ( wxFileName::MacFindDefaultTypeAndCreator(GetExt() , &type
,
2662 return MacSetTypeAndCreator( type
, creator
) ;
2667 bool wxFileName::MacFindDefaultTypeAndCreator( const wxString
& ext
, wxUint32
*type
, wxUint32
*creator
)
2669 MacEnsureDefaultExtensionsLoaded() ;
2670 wxString extl
= ext
.Lower() ;
2671 for( int i
= gMacDefaultExtensions
.Count() - 1 ; i
>= 0 ; --i
)
2673 if ( gMacDefaultExtensions
.Item(i
).m_ext
== extl
)
2675 *type
= gMacDefaultExtensions
.Item(i
).m_type
;
2676 *creator
= gMacDefaultExtensions
.Item(i
).m_creator
;
2683 void wxFileName::MacRegisterDefaultTypeAndCreator( const wxString
& ext
, wxUint32 type
, wxUint32 creator
)
2685 MacEnsureDefaultExtensionsLoaded();
2686 MacDefaultExtensionRecord
rec(ext
.Lower(), type
, creator
);
2687 gMacDefaultExtensions
.Add( rec
);
2690 #endif // defined( __WXOSX_MAC__ ) && wxOSX_USE_CARBON