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 m_hFile
= ::CreateFile
171 filename
.fn_str(), // name
172 mode
== Read
? GENERIC_READ
// access mask
174 FILE_SHARE_READ
| // sharing mode
175 FILE_SHARE_WRITE
, // (allow everything)
176 NULL
, // no secutity attr
177 OPEN_EXISTING
, // creation disposition
179 NULL
// no template file
182 if ( m_hFile
== INVALID_HANDLE_VALUE
)
186 wxLogSysError(_("Failed to open '%s' for reading"),
191 wxLogSysError(_("Failed to open '%s' for writing"),
199 if ( m_hFile
!= INVALID_HANDLE_VALUE
)
201 if ( !::CloseHandle(m_hFile
) )
203 wxLogSysError(_("Failed to close file handle"));
208 // return true only if the file could be opened successfully
209 bool IsOk() const { return m_hFile
!= INVALID_HANDLE_VALUE
; }
212 operator HANDLE() const { return m_hFile
; }
220 // ----------------------------------------------------------------------------
222 // ----------------------------------------------------------------------------
224 #if wxUSE_DATETIME && defined(__WIN32__) && !defined(__WXMICROWIN__)
226 // convert between wxDateTime and FILETIME which is a 64-bit value representing
227 // the number of 100-nanosecond intervals since January 1, 1601.
229 static void ConvertFileTimeToWx(wxDateTime
*dt
, const FILETIME
&ft
)
231 FILETIME ftcopy
= ft
;
233 if ( !::FileTimeToLocalFileTime(&ftcopy
, &ftLocal
) )
235 wxLogLastError(wxT("FileTimeToLocalFileTime"));
239 if ( !::FileTimeToSystemTime(&ftLocal
, &st
) )
241 wxLogLastError(wxT("FileTimeToSystemTime"));
244 dt
->Set(st
.wDay
, wxDateTime::Month(st
.wMonth
- 1), st
.wYear
,
245 st
.wHour
, st
.wMinute
, st
.wSecond
, st
.wMilliseconds
);
248 static void ConvertWxToFileTime(FILETIME
*ft
, const wxDateTime
& dt
)
251 st
.wDay
= dt
.GetDay();
252 st
.wMonth
= (WORD
)(dt
.GetMonth() + 1);
253 st
.wYear
= (WORD
)dt
.GetYear();
254 st
.wHour
= dt
.GetHour();
255 st
.wMinute
= dt
.GetMinute();
256 st
.wSecond
= dt
.GetSecond();
257 st
.wMilliseconds
= dt
.GetMillisecond();
260 if ( !::SystemTimeToFileTime(&st
, &ftLocal
) )
262 wxLogLastError(wxT("SystemTimeToFileTime"));
265 if ( !::LocalFileTimeToFileTime(&ftLocal
, ft
) )
267 wxLogLastError(wxT("LocalFileTimeToFileTime"));
271 #endif // wxUSE_DATETIME && __WIN32__
273 // return a string with the volume par
274 static wxString
wxGetVolumeString(const wxString
& volume
, wxPathFormat format
)
278 if ( !volume
.empty() )
280 format
= wxFileName::GetFormat(format
);
282 // Special Windows UNC paths hack, part 2: undo what we did in
283 // SplitPath() and make an UNC path if we have a drive which is not a
284 // single letter (hopefully the network shares can't be one letter only
285 // although I didn't find any authoritative docs on this)
286 if ( format
== wxPATH_DOS
&& volume
.length() > 1 )
288 path
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_DOS
<< volume
;
290 else if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
292 path
<< volume
<< wxFileName::GetVolumeSeparator(format
);
300 // return true if the character is a DOS path separator i.e. either a slash or
302 inline bool IsDOSPathSep(wxUniChar ch
)
304 return ch
== wxFILE_SEP_PATH_DOS
|| ch
== wxFILE_SEP_PATH_UNIX
;
307 // return true if the format used is the DOS/Windows one and the string looks
309 static bool IsUNCPath(const wxString
& path
, wxPathFormat format
)
311 return format
== wxPATH_DOS
&&
312 path
.length() >= 4 && // "\\a" can't be a UNC path
313 IsDOSPathSep(path
[0u]) &&
314 IsDOSPathSep(path
[1u]) &&
315 !IsDOSPathSep(path
[2u]);
318 } // anonymous namespace
320 // ============================================================================
322 // ============================================================================
324 // ----------------------------------------------------------------------------
325 // wxFileName construction
326 // ----------------------------------------------------------------------------
328 void wxFileName::Assign( const wxFileName
&filepath
)
330 m_volume
= filepath
.GetVolume();
331 m_dirs
= filepath
.GetDirs();
332 m_name
= filepath
.GetName();
333 m_ext
= filepath
.GetExt();
334 m_relative
= filepath
.m_relative
;
335 m_hasExt
= filepath
.m_hasExt
;
338 void wxFileName::Assign(const wxString
& volume
,
339 const wxString
& path
,
340 const wxString
& name
,
345 // we should ignore paths which look like UNC shares because we already
346 // have the volume here and the UNC notation (\\server\path) is only valid
347 // for paths which don't start with a volume, so prevent SetPath() from
348 // recognizing "\\foo\bar" in "c:\\foo\bar" as an UNC path
350 // note also that this is a rather ugly way to do what we want (passing
351 // some kind of flag telling to ignore UNC paths to SetPath() would be
352 // better) but this is the safest thing to do to avoid breaking backwards
353 // compatibility in 2.8
354 if ( IsUNCPath(path
, format
) )
356 // remove one of the 2 leading backslashes to ensure that it's not
357 // recognized as an UNC path by SetPath()
358 wxString
pathNonUNC(path
, 1, wxString::npos
);
359 SetPath(pathNonUNC
, format
);
361 else // no UNC complications
363 SetPath(path
, format
);
373 void wxFileName::SetPath( const wxString
& pathOrig
, wxPathFormat format
)
377 if ( pathOrig
.empty() )
385 format
= GetFormat( format
);
387 // 0) deal with possible volume part first
390 SplitVolume(pathOrig
, &volume
, &path
, format
);
391 if ( !volume
.empty() )
398 // 1) Determine if the path is relative or absolute.
402 // we had only the volume
406 wxChar leadingChar
= path
[0u];
411 m_relative
= leadingChar
== wxT(':');
413 // We then remove a leading ":". The reason is in our
414 // storage form for relative paths:
415 // ":dir:file.txt" actually means "./dir/file.txt" in
416 // DOS notation and should get stored as
417 // (relative) (dir) (file.txt)
418 // "::dir:file.txt" actually means "../dir/file.txt"
419 // stored as (relative) (..) (dir) (file.txt)
420 // This is important only for the Mac as an empty dir
421 // actually means <UP>, whereas under DOS, double
422 // slashes can be ignored: "\\\\" is the same as "\\".
428 // TODO: what is the relative path format here?
433 wxFAIL_MSG( wxT("Unknown path format") );
434 // !! Fall through !!
437 m_relative
= leadingChar
!= wxT('/');
441 m_relative
= !IsPathSeparator(leadingChar
, format
);
446 // 2) Break up the path into its members. If the original path
447 // was just "/" or "\\", m_dirs will be empty. We know from
448 // the m_relative field, if this means "nothing" or "root dir".
450 wxStringTokenizer
tn( path
, GetPathSeparators(format
) );
452 while ( tn
.HasMoreTokens() )
454 wxString token
= tn
.GetNextToken();
456 // Remove empty token under DOS and Unix, interpret them
460 if (format
== wxPATH_MAC
)
461 m_dirs
.Add( wxT("..") );
471 void wxFileName::Assign(const wxString
& fullpath
,
474 wxString volume
, path
, name
, ext
;
476 SplitPath(fullpath
, &volume
, &path
, &name
, &ext
, &hasExt
, format
);
478 Assign(volume
, path
, name
, ext
, hasExt
, format
);
481 void wxFileName::Assign(const wxString
& fullpathOrig
,
482 const wxString
& fullname
,
485 // always recognize fullpath as directory, even if it doesn't end with a
487 wxString fullpath
= fullpathOrig
;
488 if ( !fullpath
.empty() && !wxEndsWithPathSeparator(fullpath
) )
490 fullpath
+= GetPathSeparator(format
);
493 wxString volume
, path
, name
, ext
;
496 // do some consistency checks: the name should be really just the filename
497 // and the path should be really just a path
498 wxString volDummy
, pathDummy
, nameDummy
, extDummy
;
500 SplitPath(fullname
, &volDummy
, &pathDummy
, &name
, &ext
, &hasExt
, format
);
502 wxASSERT_MSG( volDummy
.empty() && pathDummy
.empty(),
503 wxT("the file name shouldn't contain the path") );
505 SplitPath(fullpath
, &volume
, &path
, &nameDummy
, &extDummy
, format
);
508 // This test makes no sense on an OpenVMS system.
509 wxASSERT_MSG( nameDummy
.empty() && extDummy
.empty(),
510 wxT("the path shouldn't contain file name nor extension") );
512 Assign(volume
, path
, name
, ext
, hasExt
, format
);
515 void wxFileName::Assign(const wxString
& pathOrig
,
516 const wxString
& name
,
522 SplitVolume(pathOrig
, &volume
, &path
, format
);
524 Assign(volume
, path
, name
, ext
, format
);
527 void wxFileName::AssignDir(const wxString
& dir
, wxPathFormat format
)
529 Assign(dir
, wxEmptyString
, format
);
532 void wxFileName::Clear()
538 m_ext
= wxEmptyString
;
540 // we don't have any absolute path for now
548 wxFileName
wxFileName::FileName(const wxString
& file
, wxPathFormat format
)
550 return wxFileName(file
, format
);
554 wxFileName
wxFileName::DirName(const wxString
& dir
, wxPathFormat format
)
557 fn
.AssignDir(dir
, format
);
561 // ----------------------------------------------------------------------------
563 // ----------------------------------------------------------------------------
565 bool wxFileName::FileExists() const
567 return wxFileName::FileExists( GetFullPath() );
570 bool wxFileName::FileExists( const wxString
&file
)
572 return ::wxFileExists( file
);
575 bool wxFileName::DirExists() const
577 return wxFileName::DirExists( GetPath() );
580 bool wxFileName::DirExists( const wxString
&dir
)
582 return ::wxDirExists( dir
);
585 // ----------------------------------------------------------------------------
586 // CWD and HOME stuff
587 // ----------------------------------------------------------------------------
589 void wxFileName::AssignCwd(const wxString
& volume
)
591 AssignDir(wxFileName::GetCwd(volume
));
595 wxString
wxFileName::GetCwd(const wxString
& volume
)
597 // if we have the volume, we must get the current directory on this drive
598 // and to do this we have to chdir to this volume - at least under Windows,
599 // I don't know how to get the current drive on another volume elsewhere
602 if ( !volume
.empty() )
605 SetCwd(volume
+ GetVolumeSeparator());
608 wxString cwd
= ::wxGetCwd();
610 if ( !volume
.empty() )
618 bool wxFileName::SetCwd() const
620 return wxFileName::SetCwd( GetPath() );
623 bool wxFileName::SetCwd( const wxString
&cwd
)
625 return ::wxSetWorkingDirectory( cwd
);
628 void wxFileName::AssignHomeDir()
630 AssignDir(wxFileName::GetHomeDir());
633 wxString
wxFileName::GetHomeDir()
635 return ::wxGetHomeDir();
639 // ----------------------------------------------------------------------------
640 // CreateTempFileName
641 // ----------------------------------------------------------------------------
643 #if wxUSE_FILE || wxUSE_FFILE
646 #if !defined wx_fdopen && defined HAVE_FDOPEN
647 #define wx_fdopen fdopen
650 // NB: GetTempFileName() under Windows creates the file, so using
651 // O_EXCL there would fail
653 #define wxOPEN_EXCL 0
655 #define wxOPEN_EXCL O_EXCL
659 #ifdef wxOpenOSFHandle
660 #define WX_HAVE_DELETE_ON_CLOSE
661 // On Windows create a file with the FILE_FLAGS_DELETE_ON_CLOSE flags.
663 static int wxOpenWithDeleteOnClose(const wxString
& filename
)
665 DWORD access
= GENERIC_READ
| GENERIC_WRITE
;
667 DWORD disposition
= OPEN_ALWAYS
;
669 DWORD attributes
= FILE_ATTRIBUTE_TEMPORARY
|
670 FILE_FLAG_DELETE_ON_CLOSE
;
672 HANDLE h
= ::CreateFile(filename
.fn_str(), access
, 0, NULL
,
673 disposition
, attributes
, NULL
);
675 return wxOpenOSFHandle(h
, wxO_BINARY
);
677 #endif // wxOpenOSFHandle
680 // Helper to open the file
682 static int wxTempOpen(const wxString
& path
, bool *deleteOnClose
)
684 #ifdef WX_HAVE_DELETE_ON_CLOSE
686 return wxOpenWithDeleteOnClose(path
);
689 *deleteOnClose
= false;
691 return wxOpen(path
, wxO_BINARY
| O_RDWR
| O_CREAT
| wxOPEN_EXCL
, 0600);
696 // Helper to open the file and attach it to the wxFFile
698 static bool wxTempOpen(wxFFile
*file
, const wxString
& path
, bool *deleteOnClose
)
701 *deleteOnClose
= false;
702 return file
->Open(path
, wxT("w+b"));
704 int fd
= wxTempOpen(path
, deleteOnClose
);
707 file
->Attach(wx_fdopen(fd
, "w+b"));
708 return file
->IsOpened();
711 #endif // wxUSE_FFILE
715 #define WXFILEARGS(x, y) y
717 #define WXFILEARGS(x, y) x
719 #define WXFILEARGS(x, y) x, y
723 // Implementation of wxFileName::CreateTempFileName().
725 static wxString
wxCreateTempImpl(
726 const wxString
& prefix
,
727 WXFILEARGS(wxFile
*fileTemp
, wxFFile
*ffileTemp
),
728 bool *deleteOnClose
= NULL
)
730 #if wxUSE_FILE && wxUSE_FFILE
731 wxASSERT(fileTemp
== NULL
|| ffileTemp
== NULL
);
733 wxString path
, dir
, name
;
734 bool wantDeleteOnClose
= false;
738 // set the result to false initially
739 wantDeleteOnClose
= *deleteOnClose
;
740 *deleteOnClose
= false;
744 // easier if it alwasys points to something
745 deleteOnClose
= &wantDeleteOnClose
;
748 // use the directory specified by the prefix
749 wxFileName::SplitPath(prefix
, &dir
, &name
, NULL
/* extension */);
753 dir
= wxFileName::GetTempDir();
756 #if defined(__WXWINCE__)
757 path
= dir
+ wxT("\\") + name
;
759 while (wxFileName::FileExists(path
))
761 path
= dir
+ wxT("\\") + name
;
766 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
767 if ( !::GetTempFileName(dir
.fn_str(), name
.fn_str(), 0,
768 wxStringBuffer(path
, MAX_PATH
+ 1)) )
770 wxLogLastError(wxT("GetTempFileName"));
778 if ( !wxEndsWithPathSeparator(dir
) &&
779 (name
.empty() || !wxIsPathSeparator(name
[0u])) )
781 path
+= wxFILE_SEP_PATH
;
786 #if defined(HAVE_MKSTEMP)
787 // scratch space for mkstemp()
788 path
+= wxT("XXXXXX");
790 // we need to copy the path to the buffer in which mkstemp() can modify it
791 wxCharBuffer
buf(path
.fn_str());
793 // cast is safe because the string length doesn't change
794 int fdTemp
= mkstemp( (char*)(const char*) buf
);
797 // this might be not necessary as mkstemp() on most systems should have
798 // already done it but it doesn't hurt neither...
801 else // mkstemp() succeeded
803 path
= wxConvFile
.cMB2WX( (const char*) buf
);
806 // avoid leaking the fd
809 fileTemp
->Attach(fdTemp
);
818 ffileTemp
->Attach(wx_fdopen(fdTemp
, "r+b"));
820 ffileTemp
->Open(path
, wxT("r+b"));
831 #else // !HAVE_MKSTEMP
835 path
+= wxT("XXXXXX");
837 wxCharBuffer buf
= wxConvFile
.cWX2MB( path
);
838 if ( !mktemp( (char*)(const char*) buf
) )
844 path
= wxConvFile
.cMB2WX( (const char*) buf
);
846 #else // !HAVE_MKTEMP (includes __DOS__)
847 // generate the unique file name ourselves
848 #if !defined(__DOS__) && !defined(__PALMOS__) && (!defined(__MWERKS__) || defined(__DARWIN__) )
849 path
<< (unsigned int)getpid();
854 static const size_t numTries
= 1000;
855 for ( size_t n
= 0; n
< numTries
; n
++ )
857 // 3 hex digits is enough for numTries == 1000 < 4096
858 pathTry
= path
+ wxString::Format(wxT("%.03x"), (unsigned int) n
);
859 if ( !wxFileName::FileExists(pathTry
) )
868 #endif // HAVE_MKTEMP/!HAVE_MKTEMP
870 #endif // HAVE_MKSTEMP/!HAVE_MKSTEMP
872 #endif // Windows/!Windows
876 wxLogSysError(_("Failed to create a temporary file name"));
882 // open the file - of course, there is a race condition here, this is
883 // why we always prefer using mkstemp()...
885 if ( fileTemp
&& !fileTemp
->IsOpened() )
887 *deleteOnClose
= wantDeleteOnClose
;
888 int fd
= wxTempOpen(path
, deleteOnClose
);
890 fileTemp
->Attach(fd
);
897 if ( ffileTemp
&& !ffileTemp
->IsOpened() )
899 *deleteOnClose
= wantDeleteOnClose
;
900 ok
= wxTempOpen(ffileTemp
, path
, deleteOnClose
);
906 // FIXME: If !ok here should we loop and try again with another
907 // file name? That is the standard recourse if open(O_EXCL)
908 // fails, though of course it should be protected against
909 // possible infinite looping too.
911 wxLogError(_("Failed to open temporary file."));
921 static bool wxCreateTempImpl(
922 const wxString
& prefix
,
923 WXFILEARGS(wxFile
*fileTemp
, wxFFile
*ffileTemp
),
926 bool deleteOnClose
= true;
928 *name
= wxCreateTempImpl(prefix
,
929 WXFILEARGS(fileTemp
, ffileTemp
),
932 bool ok
= !name
->empty();
937 else if (ok
&& wxRemoveFile(*name
))
945 static void wxAssignTempImpl(
947 const wxString
& prefix
,
948 WXFILEARGS(wxFile
*fileTemp
, wxFFile
*ffileTemp
))
951 tempname
= wxCreateTempImpl(prefix
, WXFILEARGS(fileTemp
, ffileTemp
));
953 if ( tempname
.empty() )
955 // error, failed to get temp file name
960 fn
->Assign(tempname
);
965 void wxFileName::AssignTempFileName(const wxString
& prefix
)
967 wxAssignTempImpl(this, prefix
, WXFILEARGS(NULL
, NULL
));
971 wxString
wxFileName::CreateTempFileName(const wxString
& prefix
)
973 return wxCreateTempImpl(prefix
, WXFILEARGS(NULL
, NULL
));
976 #endif // wxUSE_FILE || wxUSE_FFILE
981 wxString
wxCreateTempFileName(const wxString
& prefix
,
985 return wxCreateTempImpl(prefix
, WXFILEARGS(fileTemp
, NULL
), deleteOnClose
);
988 bool wxCreateTempFile(const wxString
& prefix
,
992 return wxCreateTempImpl(prefix
, WXFILEARGS(fileTemp
, NULL
), name
);
995 void wxFileName::AssignTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
997 wxAssignTempImpl(this, prefix
, WXFILEARGS(fileTemp
, NULL
));
1002 wxFileName::CreateTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
1004 return wxCreateTempFileName(prefix
, fileTemp
);
1007 #endif // wxUSE_FILE
1012 wxString
wxCreateTempFileName(const wxString
& prefix
,
1014 bool *deleteOnClose
)
1016 return wxCreateTempImpl(prefix
, WXFILEARGS(NULL
, fileTemp
), deleteOnClose
);
1019 bool wxCreateTempFile(const wxString
& prefix
,
1023 return wxCreateTempImpl(prefix
, WXFILEARGS(NULL
, fileTemp
), name
);
1027 void wxFileName::AssignTempFileName(const wxString
& prefix
, wxFFile
*fileTemp
)
1029 wxAssignTempImpl(this, prefix
, WXFILEARGS(NULL
, fileTemp
));
1034 wxFileName::CreateTempFileName(const wxString
& prefix
, wxFFile
*fileTemp
)
1036 return wxCreateTempFileName(prefix
, fileTemp
);
1039 #endif // wxUSE_FFILE
1042 // ----------------------------------------------------------------------------
1043 // directory operations
1044 // ----------------------------------------------------------------------------
1046 // helper of GetTempDir(): check if the given directory exists and return it if
1047 // it does or an empty string otherwise
1051 wxString
CheckIfDirExists(const wxString
& dir
)
1053 return wxFileName::DirExists(dir
) ? dir
: wxString();
1056 } // anonymous namespace
1058 wxString
wxFileName::GetTempDir()
1060 // first try getting it from environment: this allows overriding the values
1061 // used by default if the user wants to create temporary files in another
1063 wxString dir
= CheckIfDirExists(wxGetenv("TMPDIR"));
1066 dir
= CheckIfDirExists(wxGetenv("TMP"));
1068 dir
= CheckIfDirExists(wxGetenv("TEMP"));
1071 // if no environment variables are set, use the system default
1074 #if defined(__WXWINCE__)
1075 dir
= CheckIfDirExists(wxT("\\temp"));
1076 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1077 if ( !::GetTempPath(MAX_PATH
, wxStringBuffer(dir
, MAX_PATH
+ 1)) )
1079 wxLogLastError(wxT("GetTempPath"));
1081 #elif defined(__WXMAC__) && wxOSX_USE_CARBON
1082 dir
= wxMacFindFolder(short(kOnSystemDisk
), kTemporaryFolderType
, kCreateFolder
);
1083 #endif // systems with native way
1086 // fall back to hard coded value
1089 #ifdef __UNIX_LIKE__
1090 dir
= CheckIfDirExists("/tmp");
1092 #endif // __UNIX_LIKE__
1099 bool wxFileName::Mkdir( int perm
, int flags
) const
1101 return wxFileName::Mkdir(GetPath(), perm
, flags
);
1104 bool wxFileName::Mkdir( const wxString
& dir
, int perm
, int flags
)
1106 if ( flags
& wxPATH_MKDIR_FULL
)
1108 // split the path in components
1109 wxFileName filename
;
1110 filename
.AssignDir(dir
);
1113 if ( filename
.HasVolume())
1115 currPath
<< wxGetVolumeString(filename
.GetVolume(), wxPATH_NATIVE
);
1118 wxArrayString dirs
= filename
.GetDirs();
1119 size_t count
= dirs
.GetCount();
1120 for ( size_t i
= 0; i
< count
; i
++ )
1122 if ( i
> 0 || filename
.IsAbsolute() )
1123 currPath
+= wxFILE_SEP_PATH
;
1124 currPath
+= dirs
[i
];
1126 if (!DirExists(currPath
))
1128 if (!wxMkdir(currPath
, perm
))
1130 // no need to try creating further directories
1140 return ::wxMkdir( dir
, perm
);
1143 bool wxFileName::Rmdir(int flags
) const
1145 return wxFileName::Rmdir( GetPath(), flags
);
1148 bool wxFileName::Rmdir(const wxString
& dir
, int flags
)
1151 if ( flags
& wxPATH_RMDIR_RECURSIVE
)
1153 // SHFileOperation needs double null termination string
1154 // but without separator at the end of the path
1156 if ( path
.Last() == wxFILE_SEP_PATH
)
1160 SHFILEOPSTRUCT fileop
;
1161 wxZeroMemory(fileop
);
1162 fileop
.wFunc
= FO_DELETE
;
1163 fileop
.pFrom
= path
.fn_str();
1164 fileop
.fFlags
= FOF_SILENT
| FOF_NOCONFIRMATION
;
1166 // FOF_NOERRORUI is not defined in WinCE
1167 fileop
.fFlags
|= FOF_NOERRORUI
;
1170 int ret
= SHFileOperation(&fileop
);
1173 // SHFileOperation may return non-Win32 error codes, so the error
1174 // message can be incorrect
1175 wxLogApiError(wxT("SHFileOperation"), ret
);
1181 else if ( flags
& wxPATH_RMDIR_FULL
)
1183 if ( flags
!= 0 ) // wxPATH_RMDIR_FULL or wxPATH_RMDIR_RECURSIVE
1184 #endif // !__WXMSW__
1187 if ( path
.Last() != wxFILE_SEP_PATH
)
1188 path
+= wxFILE_SEP_PATH
;
1192 if ( !d
.IsOpened() )
1197 // first delete all subdirectories
1198 bool cont
= d
.GetFirst(&filename
, "", wxDIR_DIRS
| wxDIR_HIDDEN
);
1201 wxFileName::Rmdir(path
+ filename
, flags
);
1202 cont
= d
.GetNext(&filename
);
1206 if ( flags
& wxPATH_RMDIR_RECURSIVE
)
1208 // delete all files too
1209 cont
= d
.GetFirst(&filename
, "", wxDIR_FILES
| wxDIR_HIDDEN
);
1212 ::wxRemoveFile(path
+ filename
);
1213 cont
= d
.GetNext(&filename
);
1216 #endif // !__WXMSW__
1219 return ::wxRmdir(dir
);
1222 // ----------------------------------------------------------------------------
1223 // path normalization
1224 // ----------------------------------------------------------------------------
1226 bool wxFileName::Normalize(int flags
,
1227 const wxString
& cwd
,
1228 wxPathFormat format
)
1230 // deal with env vars renaming first as this may seriously change the path
1231 if ( flags
& wxPATH_NORM_ENV_VARS
)
1233 wxString pathOrig
= GetFullPath(format
);
1234 wxString path
= wxExpandEnvVars(pathOrig
);
1235 if ( path
!= pathOrig
)
1241 // the existing path components
1242 wxArrayString dirs
= GetDirs();
1244 // the path to prepend in front to make the path absolute
1247 format
= GetFormat(format
);
1249 // set up the directory to use for making the path absolute later
1250 if ( (flags
& wxPATH_NORM_ABSOLUTE
) && !IsAbsolute(format
) )
1254 curDir
.AssignCwd(GetVolume());
1256 else // cwd provided
1258 curDir
.AssignDir(cwd
);
1262 // handle ~ stuff under Unix only
1263 if ( (format
== wxPATH_UNIX
) && (flags
& wxPATH_NORM_TILDE
) && m_relative
)
1265 if ( !dirs
.IsEmpty() )
1267 wxString dir
= dirs
[0u];
1268 if ( !dir
.empty() && dir
[0u] == wxT('~') )
1270 // to make the path absolute use the home directory
1271 curDir
.AssignDir(wxGetUserHome(dir
.c_str() + 1));
1277 // transform relative path into abs one
1278 if ( curDir
.IsOk() )
1280 // this path may be relative because it doesn't have the volume name
1281 // and still have m_relative=true; in this case we shouldn't modify
1282 // our directory components but just set the current volume
1283 if ( !HasVolume() && curDir
.HasVolume() )
1285 SetVolume(curDir
.GetVolume());
1289 // yes, it was the case - we don't need curDir then
1294 // finally, prepend curDir to the dirs array
1295 wxArrayString dirsNew
= curDir
.GetDirs();
1296 WX_PREPEND_ARRAY(dirs
, dirsNew
);
1298 // if we used e.g. tilde expansion previously and wxGetUserHome didn't
1299 // return for some reason an absolute path, then curDir maybe not be absolute!
1300 if ( !curDir
.m_relative
)
1302 // we have prepended an absolute path and thus we are now an absolute
1306 // else if (flags & wxPATH_NORM_ABSOLUTE):
1307 // should we warn the user that we didn't manage to make the path absolute?
1310 // now deal with ".", ".." and the rest
1312 size_t count
= dirs
.GetCount();
1313 for ( size_t n
= 0; n
< count
; n
++ )
1315 wxString dir
= dirs
[n
];
1317 if ( flags
& wxPATH_NORM_DOTS
)
1319 if ( dir
== wxT(".") )
1325 if ( dir
== wxT("..") )
1327 if ( m_dirs
.IsEmpty() )
1329 wxLogError(_("The path '%s' contains too many \"..\"!"),
1330 GetFullPath().c_str());
1334 m_dirs
.RemoveAt(m_dirs
.GetCount() - 1);
1342 #if defined(__WIN32__) && !defined(__WXWINCE__) && wxUSE_OLE
1343 if ( (flags
& wxPATH_NORM_SHORTCUT
) )
1346 if (GetShortcutTarget(GetFullPath(format
), filename
))
1354 #if defined(__WIN32__)
1355 if ( (flags
& wxPATH_NORM_LONG
) && (format
== wxPATH_DOS
) )
1357 Assign(GetLongPath());
1361 // Change case (this should be kept at the end of the function, to ensure
1362 // that the path doesn't change any more after we normalize its case)
1363 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
1365 m_volume
.MakeLower();
1369 // directory entries must be made lower case as well
1370 count
= m_dirs
.GetCount();
1371 for ( size_t i
= 0; i
< count
; i
++ )
1373 m_dirs
[i
].MakeLower();
1381 bool wxFileName::ReplaceEnvVariable(const wxString
& envname
,
1382 const wxString
& replacementFmtString
,
1383 wxPathFormat format
)
1385 // look into stringForm for the contents of the given environment variable
1387 if (envname
.empty() ||
1388 !wxGetEnv(envname
, &val
))
1393 wxString stringForm
= GetPath(wxPATH_GET_VOLUME
, format
);
1394 // do not touch the file name and the extension
1396 wxString replacement
= wxString::Format(replacementFmtString
, envname
);
1397 stringForm
.Replace(val
, replacement
);
1399 // Now assign ourselves the modified path:
1400 Assign(stringForm
, GetFullName(), format
);
1406 bool wxFileName::ReplaceHomeDir(wxPathFormat format
)
1408 wxString homedir
= wxGetHomeDir();
1409 if (homedir
.empty())
1412 wxString stringForm
= GetPath(wxPATH_GET_VOLUME
, format
);
1413 // do not touch the file name and the extension
1415 stringForm
.Replace(homedir
, "~");
1417 // Now assign ourselves the modified path:
1418 Assign(stringForm
, GetFullName(), format
);
1423 // ----------------------------------------------------------------------------
1424 // get the shortcut target
1425 // ----------------------------------------------------------------------------
1427 // WinCE (3) doesn't have CLSID_ShellLink, IID_IShellLink definitions.
1428 // The .lnk file is a plain text file so it should be easy to
1429 // make it work. Hint from Google Groups:
1430 // "If you open up a lnk file, you'll see a
1431 // number, followed by a pound sign (#), followed by more text. The
1432 // number is the number of characters that follows the pound sign. The
1433 // characters after the pound sign are the command line (which _can_
1434 // include arguments) to be executed. Any path (e.g. \windows\program
1435 // files\myapp.exe) that includes spaces needs to be enclosed in
1436 // quotation marks."
1438 #if defined(__WIN32__) && !defined(__WXWINCE__) && wxUSE_OLE
1439 // The following lines are necessary under WinCE
1440 // #include "wx/msw/private.h"
1441 // #include <ole2.h>
1443 #if defined(__WXWINCE__)
1444 #include <shlguid.h>
1447 bool wxFileName::GetShortcutTarget(const wxString
& shortcutPath
,
1448 wxString
& targetFilename
,
1449 wxString
* arguments
) const
1451 wxString path
, file
, ext
;
1452 wxFileName::SplitPath(shortcutPath
, & path
, & file
, & ext
);
1456 bool success
= false;
1458 // Assume it's not a shortcut if it doesn't end with lnk
1459 if (ext
.CmpNoCase(wxT("lnk"))!=0)
1462 // create a ShellLink object
1463 hres
= CoCreateInstance(CLSID_ShellLink
, NULL
, CLSCTX_INPROC_SERVER
,
1464 IID_IShellLink
, (LPVOID
*) &psl
);
1466 if (SUCCEEDED(hres
))
1469 hres
= psl
->QueryInterface( IID_IPersistFile
, (LPVOID
*) &ppf
);
1470 if (SUCCEEDED(hres
))
1472 WCHAR wsz
[MAX_PATH
];
1474 MultiByteToWideChar(CP_ACP
, MB_PRECOMPOSED
, shortcutPath
.mb_str(), -1, wsz
,
1477 hres
= ppf
->Load(wsz
, 0);
1480 if (SUCCEEDED(hres
))
1483 // Wrong prototype in early versions
1484 #if defined(__MINGW32__) && !wxCHECK_W32API_VERSION(2, 2)
1485 psl
->GetPath((CHAR
*) buf
, 2048, NULL
, SLGP_UNCPRIORITY
);
1487 psl
->GetPath(buf
, 2048, NULL
, SLGP_UNCPRIORITY
);
1489 targetFilename
= wxString(buf
);
1490 success
= (shortcutPath
!= targetFilename
);
1492 psl
->GetArguments(buf
, 2048);
1494 if (!args
.empty() && arguments
)
1506 #endif // __WIN32__ && !__WXWINCE__
1509 // ----------------------------------------------------------------------------
1510 // absolute/relative paths
1511 // ----------------------------------------------------------------------------
1513 bool wxFileName::IsAbsolute(wxPathFormat format
) const
1515 // unix paths beginning with ~ are reported as being absolute
1516 if ( format
== wxPATH_UNIX
)
1518 if ( !m_dirs
.IsEmpty() )
1520 wxString dir
= m_dirs
[0u];
1522 if (!dir
.empty() && dir
[0u] == wxT('~'))
1527 // if our path doesn't start with a path separator, it's not an absolute
1532 if ( !GetVolumeSeparator(format
).empty() )
1534 // this format has volumes and an absolute path must have one, it's not
1535 // enough to have the full path to be an absolute file under Windows
1536 if ( GetVolume().empty() )
1543 bool wxFileName::MakeRelativeTo(const wxString
& pathBase
, wxPathFormat format
)
1545 wxFileName fnBase
= wxFileName::DirName(pathBase
, format
);
1547 // get cwd only once - small time saving
1548 wxString cwd
= wxGetCwd();
1549 Normalize(wxPATH_NORM_ALL
& ~wxPATH_NORM_CASE
, cwd
, format
);
1550 fnBase
.Normalize(wxPATH_NORM_ALL
& ~wxPATH_NORM_CASE
, cwd
, format
);
1552 bool withCase
= IsCaseSensitive(format
);
1554 // we can't do anything if the files live on different volumes
1555 if ( !GetVolume().IsSameAs(fnBase
.GetVolume(), withCase
) )
1561 // same drive, so we don't need our volume
1564 // remove common directories starting at the top
1565 while ( !m_dirs
.IsEmpty() && !fnBase
.m_dirs
.IsEmpty() &&
1566 m_dirs
[0u].IsSameAs(fnBase
.m_dirs
[0u], withCase
) )
1569 fnBase
.m_dirs
.RemoveAt(0);
1572 // add as many ".." as needed
1573 size_t count
= fnBase
.m_dirs
.GetCount();
1574 for ( size_t i
= 0; i
< count
; i
++ )
1576 m_dirs
.Insert(wxT(".."), 0u);
1579 if ( format
== wxPATH_UNIX
|| format
== wxPATH_DOS
)
1581 // a directory made relative with respect to itself is '.' under Unix
1582 // and DOS, by definition (but we don't have to insert "./" for the
1584 if ( m_dirs
.IsEmpty() && IsDir() )
1586 m_dirs
.Add(wxT('.'));
1596 // ----------------------------------------------------------------------------
1597 // filename kind tests
1598 // ----------------------------------------------------------------------------
1600 bool wxFileName::SameAs(const wxFileName
& filepath
, wxPathFormat format
) const
1602 wxFileName fn1
= *this,
1605 // get cwd only once - small time saving
1606 wxString cwd
= wxGetCwd();
1607 fn1
.Normalize(wxPATH_NORM_ALL
| wxPATH_NORM_CASE
, cwd
, format
);
1608 fn2
.Normalize(wxPATH_NORM_ALL
| wxPATH_NORM_CASE
, cwd
, format
);
1610 if ( fn1
.GetFullPath() == fn2
.GetFullPath() )
1613 // TODO: compare inodes for Unix, this works even when filenames are
1614 // different but files are the same (symlinks) (VZ)
1620 bool wxFileName::IsCaseSensitive( wxPathFormat format
)
1622 // only Unix filenames are truely case-sensitive
1623 return GetFormat(format
) == wxPATH_UNIX
;
1627 wxString
wxFileName::GetForbiddenChars(wxPathFormat format
)
1629 // Inits to forbidden characters that are common to (almost) all platforms.
1630 wxString strForbiddenChars
= wxT("*?");
1632 // If asserts, wxPathFormat has been changed. In case of a new path format
1633 // addition, the following code might have to be updated.
1634 wxCOMPILE_TIME_ASSERT(wxPATH_MAX
== 5, wxPathFormatChanged
);
1635 switch ( GetFormat(format
) )
1638 wxFAIL_MSG( wxT("Unknown path format") );
1639 // !! Fall through !!
1645 // On a Mac even names with * and ? are allowed (Tested with OS
1646 // 9.2.1 and OS X 10.2.5)
1647 strForbiddenChars
= wxEmptyString
;
1651 strForbiddenChars
+= wxT("\\/:\"<>|");
1658 return strForbiddenChars
;
1662 wxString
wxFileName::GetVolumeSeparator(wxPathFormat
WXUNUSED_IN_WINCE(format
))
1665 return wxEmptyString
;
1669 if ( (GetFormat(format
) == wxPATH_DOS
) ||
1670 (GetFormat(format
) == wxPATH_VMS
) )
1672 sepVol
= wxFILE_SEP_DSK
;
1681 wxString
wxFileName::GetPathSeparators(wxPathFormat format
)
1684 switch ( GetFormat(format
) )
1687 // accept both as native APIs do but put the native one first as
1688 // this is the one we use in GetFullPath()
1689 seps
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_UNIX
;
1693 wxFAIL_MSG( wxT("Unknown wxPATH_XXX style") );
1697 seps
= wxFILE_SEP_PATH_UNIX
;
1701 seps
= wxFILE_SEP_PATH_MAC
;
1705 seps
= wxFILE_SEP_PATH_VMS
;
1713 wxString
wxFileName::GetPathTerminators(wxPathFormat format
)
1715 format
= GetFormat(format
);
1717 // under VMS the end of the path is ']', not the path separator used to
1718 // separate the components
1719 return format
== wxPATH_VMS
? wxString(wxT(']')) : GetPathSeparators(format
);
1723 bool wxFileName::IsPathSeparator(wxChar ch
, wxPathFormat format
)
1725 // wxString::Find() doesn't work as expected with NUL - it will always find
1726 // it, so test for it separately
1727 return ch
!= wxT('\0') && GetPathSeparators(format
).Find(ch
) != wxNOT_FOUND
;
1730 // ----------------------------------------------------------------------------
1731 // path components manipulation
1732 // ----------------------------------------------------------------------------
1734 /* static */ bool wxFileName::IsValidDirComponent(const wxString
& dir
)
1738 wxFAIL_MSG( wxT("empty directory passed to wxFileName::InsertDir()") );
1743 const size_t len
= dir
.length();
1744 for ( size_t n
= 0; n
< len
; n
++ )
1746 if ( dir
[n
] == GetVolumeSeparator() || IsPathSeparator(dir
[n
]) )
1748 wxFAIL_MSG( wxT("invalid directory component in wxFileName") );
1757 void wxFileName::AppendDir( const wxString
& dir
)
1759 if ( IsValidDirComponent(dir
) )
1763 void wxFileName::PrependDir( const wxString
& dir
)
1768 void wxFileName::InsertDir(size_t before
, const wxString
& dir
)
1770 if ( IsValidDirComponent(dir
) )
1771 m_dirs
.Insert(dir
, before
);
1774 void wxFileName::RemoveDir(size_t pos
)
1776 m_dirs
.RemoveAt(pos
);
1779 // ----------------------------------------------------------------------------
1781 // ----------------------------------------------------------------------------
1783 void wxFileName::SetFullName(const wxString
& fullname
)
1785 SplitPath(fullname
, NULL
/* no volume */, NULL
/* no path */,
1786 &m_name
, &m_ext
, &m_hasExt
);
1789 wxString
wxFileName::GetFullName() const
1791 wxString fullname
= m_name
;
1794 fullname
<< wxFILE_SEP_EXT
<< m_ext
;
1800 wxString
wxFileName::GetPath( int flags
, wxPathFormat format
) const
1802 format
= GetFormat( format
);
1806 // return the volume with the path as well if requested
1807 if ( flags
& wxPATH_GET_VOLUME
)
1809 fullpath
+= wxGetVolumeString(GetVolume(), format
);
1812 // the leading character
1817 fullpath
+= wxFILE_SEP_PATH_MAC
;
1822 fullpath
+= wxFILE_SEP_PATH_DOS
;
1826 wxFAIL_MSG( wxT("Unknown path format") );
1832 fullpath
+= wxFILE_SEP_PATH_UNIX
;
1837 // no leading character here but use this place to unset
1838 // wxPATH_GET_SEPARATOR flag: under VMS it doesn't make sense
1839 // as, if I understand correctly, there should never be a dot
1840 // before the closing bracket
1841 flags
&= ~wxPATH_GET_SEPARATOR
;
1844 if ( m_dirs
.empty() )
1846 // there is nothing more
1850 // then concatenate all the path components using the path separator
1851 if ( format
== wxPATH_VMS
)
1853 fullpath
+= wxT('[');
1856 const size_t dirCount
= m_dirs
.GetCount();
1857 for ( size_t i
= 0; i
< dirCount
; i
++ )
1862 if ( m_dirs
[i
] == wxT(".") )
1864 // skip appending ':', this shouldn't be done in this
1865 // case as "::" is interpreted as ".." under Unix
1869 // convert back from ".." to nothing
1870 if ( !m_dirs
[i
].IsSameAs(wxT("..")) )
1871 fullpath
+= m_dirs
[i
];
1875 wxFAIL_MSG( wxT("Unexpected path format") );
1876 // still fall through
1880 fullpath
+= m_dirs
[i
];
1884 // TODO: What to do with ".." under VMS
1886 // convert back from ".." to nothing
1887 if ( !m_dirs
[i
].IsSameAs(wxT("..")) )
1888 fullpath
+= m_dirs
[i
];
1892 if ( (flags
& wxPATH_GET_SEPARATOR
) || (i
!= dirCount
- 1) )
1893 fullpath
+= GetPathSeparator(format
);
1896 if ( format
== wxPATH_VMS
)
1898 fullpath
+= wxT(']');
1904 wxString
wxFileName::GetFullPath( wxPathFormat format
) const
1906 // we already have a function to get the path
1907 wxString fullpath
= GetPath(wxPATH_GET_VOLUME
| wxPATH_GET_SEPARATOR
,
1910 // now just add the file name and extension to it
1911 fullpath
+= GetFullName();
1916 // Return the short form of the path (returns identity on non-Windows platforms)
1917 wxString
wxFileName::GetShortPath() const
1919 wxString
path(GetFullPath());
1921 #if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
1922 DWORD sz
= ::GetShortPathName(path
.fn_str(), NULL
, 0);
1926 if ( ::GetShortPathName
1929 wxStringBuffer(pathOut
, sz
),
1941 // Return the long form of the path (returns identity on non-Windows platforms)
1942 wxString
wxFileName::GetLongPath() const
1945 path
= GetFullPath();
1947 #if defined(__WIN32__) && !defined(__WXWINCE__) && !defined(__WXMICROWIN__)
1949 #if wxUSE_DYNLIB_CLASS
1950 typedef DWORD (WINAPI
*GET_LONG_PATH_NAME
)(const wxChar
*, wxChar
*, DWORD
);
1952 // this is MT-safe as in the worst case we're going to resolve the function
1953 // twice -- but as the result is the same in both threads, it's ok
1954 static GET_LONG_PATH_NAME s_pfnGetLongPathName
= NULL
;
1955 if ( !s_pfnGetLongPathName
)
1957 static bool s_triedToLoad
= false;
1959 if ( !s_triedToLoad
)
1961 s_triedToLoad
= true;
1963 wxDynamicLibrary
dllKernel(wxT("kernel32"));
1965 const wxChar
* GetLongPathName
= wxT("GetLongPathName")
1970 #endif // Unicode/ANSI
1972 if ( dllKernel
.HasSymbol(GetLongPathName
) )
1974 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
)
1975 dllKernel
.GetSymbol(GetLongPathName
);
1978 // note that kernel32.dll can be unloaded, it stays in memory
1979 // anyhow as all Win32 programs link to it and so it's safe to call
1980 // GetLongPathName() even after unloading it
1984 if ( s_pfnGetLongPathName
)
1986 DWORD dwSize
= (*s_pfnGetLongPathName
)(path
.fn_str(), NULL
, 0);
1989 if ( (*s_pfnGetLongPathName
)
1992 wxStringBuffer(pathOut
, dwSize
),
2000 #endif // wxUSE_DYNLIB_CLASS
2002 // The OS didn't support GetLongPathName, or some other error.
2003 // We need to call FindFirstFile on each component in turn.
2005 WIN32_FIND_DATA findFileData
;
2009 pathOut
= GetVolume() +
2010 GetVolumeSeparator(wxPATH_DOS
) +
2011 GetPathSeparator(wxPATH_DOS
);
2013 pathOut
= wxEmptyString
;
2015 wxArrayString dirs
= GetDirs();
2016 dirs
.Add(GetFullName());
2020 size_t count
= dirs
.GetCount();
2021 for ( size_t i
= 0; i
< count
; i
++ )
2023 const wxString
& dir
= dirs
[i
];
2025 // We're using pathOut to collect the long-name path, but using a
2026 // temporary for appending the last path component which may be
2028 tmpPath
= pathOut
+ dir
;
2030 // We must not process "." or ".." here as they would be (unexpectedly)
2031 // replaced by the corresponding directory names so just leave them
2034 // And we can't pass a drive and root dir to FindFirstFile (VZ: why?)
2035 if ( tmpPath
.empty() || dir
== '.' || dir
== ".." ||
2036 tmpPath
.Last() == GetVolumeSeparator(wxPATH_DOS
) )
2038 tmpPath
+= wxFILE_SEP_PATH
;
2043 hFind
= ::FindFirstFile(tmpPath
.fn_str(), &findFileData
);
2044 if (hFind
== INVALID_HANDLE_VALUE
)
2046 // Error: most likely reason is that path doesn't exist, so
2047 // append any unprocessed parts and return
2048 for ( i
+= 1; i
< count
; i
++ )
2049 tmpPath
+= wxFILE_SEP_PATH
+ dirs
[i
];
2054 pathOut
+= findFileData
.cFileName
;
2055 if ( (i
< (count
-1)) )
2056 pathOut
+= wxFILE_SEP_PATH
;
2062 #endif // Win32/!Win32
2067 wxPathFormat
wxFileName::GetFormat( wxPathFormat format
)
2069 if (format
== wxPATH_NATIVE
)
2071 #if defined(__WXMSW__) || defined(__OS2__) || defined(__DOS__)
2072 format
= wxPATH_DOS
;
2073 #elif defined(__VMS)
2074 format
= wxPATH_VMS
;
2076 format
= wxPATH_UNIX
;
2082 #ifdef wxHAS_FILESYSTEM_VOLUMES
2085 wxString
wxFileName::GetVolumeString(char drive
, int flags
)
2087 wxASSERT_MSG( !(flags
& ~wxPATH_GET_SEPARATOR
), "invalid flag specified" );
2089 wxString
vol(drive
);
2090 vol
+= wxFILE_SEP_DSK
;
2091 if ( flags
& wxPATH_GET_SEPARATOR
)
2092 vol
+= wxFILE_SEP_PATH
;
2097 #endif // wxHAS_FILESYSTEM_VOLUMES
2099 // ----------------------------------------------------------------------------
2100 // path splitting function
2101 // ----------------------------------------------------------------------------
2105 wxFileName::SplitVolume(const wxString
& fullpathWithVolume
,
2106 wxString
*pstrVolume
,
2108 wxPathFormat format
)
2110 format
= GetFormat(format
);
2112 wxString fullpath
= fullpathWithVolume
;
2114 // special Windows UNC paths hack: transform \\share\path into share:path
2115 if ( IsUNCPath(fullpath
, format
) )
2117 fullpath
.erase(0, 2);
2119 size_t posFirstSlash
=
2120 fullpath
.find_first_of(GetPathTerminators(format
));
2121 if ( posFirstSlash
!= wxString::npos
)
2123 fullpath
[posFirstSlash
] = wxFILE_SEP_DSK
;
2125 // UNC paths are always absolute, right? (FIXME)
2126 fullpath
.insert(posFirstSlash
+ 1, 1, wxFILE_SEP_PATH_DOS
);
2130 // We separate the volume here
2131 if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
2133 wxString sepVol
= GetVolumeSeparator(format
);
2135 // we have to exclude the case of a colon in the very beginning of the
2136 // string as it can't be a volume separator (nor can this be a valid
2137 // DOS file name at all but we'll leave dealing with this to our caller)
2138 size_t posFirstColon
= fullpath
.find_first_of(sepVol
);
2139 if ( posFirstColon
&& posFirstColon
!= wxString::npos
)
2143 *pstrVolume
= fullpath
.Left(posFirstColon
);
2146 // remove the volume name and the separator from the full path
2147 fullpath
.erase(0, posFirstColon
+ sepVol
.length());
2152 *pstrPath
= fullpath
;
2156 void wxFileName::SplitPath(const wxString
& fullpathWithVolume
,
2157 wxString
*pstrVolume
,
2162 wxPathFormat format
)
2164 format
= GetFormat(format
);
2167 SplitVolume(fullpathWithVolume
, pstrVolume
, &fullpath
, format
);
2169 // find the positions of the last dot and last path separator in the path
2170 size_t posLastDot
= fullpath
.find_last_of(wxFILE_SEP_EXT
);
2171 size_t posLastSlash
= fullpath
.find_last_of(GetPathTerminators(format
));
2173 // check whether this dot occurs at the very beginning of a path component
2174 if ( (posLastDot
!= wxString::npos
) &&
2176 IsPathSeparator(fullpath
[posLastDot
- 1]) ||
2177 (format
== wxPATH_VMS
&& fullpath
[posLastDot
- 1] == wxT(']'))) )
2179 // dot may be (and commonly -- at least under Unix -- is) the first
2180 // character of the filename, don't treat the entire filename as
2181 // extension in this case
2182 posLastDot
= wxString::npos
;
2185 // if we do have a dot and a slash, check that the dot is in the name part
2186 if ( (posLastDot
!= wxString::npos
) &&
2187 (posLastSlash
!= wxString::npos
) &&
2188 (posLastDot
< posLastSlash
) )
2190 // the dot is part of the path, not the start of the extension
2191 posLastDot
= wxString::npos
;
2194 // now fill in the variables provided by user
2197 if ( posLastSlash
== wxString::npos
)
2204 // take everything up to the path separator but take care to make
2205 // the path equal to something like '/', not empty, for the files
2206 // immediately under root directory
2207 size_t len
= posLastSlash
;
2209 // this rule does not apply to mac since we do not start with colons (sep)
2210 // except for relative paths
2211 if ( !len
&& format
!= wxPATH_MAC
)
2214 *pstrPath
= fullpath
.Left(len
);
2216 // special VMS hack: remove the initial bracket
2217 if ( format
== wxPATH_VMS
)
2219 if ( (*pstrPath
)[0u] == wxT('[') )
2220 pstrPath
->erase(0, 1);
2227 // take all characters starting from the one after the last slash and
2228 // up to, but excluding, the last dot
2229 size_t nStart
= posLastSlash
== wxString::npos
? 0 : posLastSlash
+ 1;
2231 if ( posLastDot
== wxString::npos
)
2233 // take all until the end
2234 count
= wxString::npos
;
2236 else if ( posLastSlash
== wxString::npos
)
2240 else // have both dot and slash
2242 count
= posLastDot
- posLastSlash
- 1;
2245 *pstrName
= fullpath
.Mid(nStart
, count
);
2248 // finally deal with the extension here: we have an added complication that
2249 // extension may be empty (but present) as in "foo." where trailing dot
2250 // indicates the empty extension at the end -- and hence we must remember
2251 // that we have it independently of pstrExt
2252 if ( posLastDot
== wxString::npos
)
2262 // take everything after the dot
2264 *pstrExt
= fullpath
.Mid(posLastDot
+ 1);
2271 void wxFileName::SplitPath(const wxString
& fullpath
,
2275 wxPathFormat format
)
2278 SplitPath(fullpath
, &volume
, path
, name
, ext
, format
);
2282 path
->Prepend(wxGetVolumeString(volume
, format
));
2287 wxString
wxFileName::StripExtension(const wxString
& fullpath
)
2289 wxFileName
fn(fullpath
);
2291 return fn
.GetFullPath();
2294 // ----------------------------------------------------------------------------
2296 // ----------------------------------------------------------------------------
2300 bool wxFileName::SetTimes(const wxDateTime
*dtAccess
,
2301 const wxDateTime
*dtMod
,
2302 const wxDateTime
*dtCreate
) const
2304 #if defined(__WIN32__)
2305 FILETIME ftAccess
, ftCreate
, ftWrite
;
2308 ConvertWxToFileTime(&ftCreate
, *dtCreate
);
2310 ConvertWxToFileTime(&ftAccess
, *dtAccess
);
2312 ConvertWxToFileTime(&ftWrite
, *dtMod
);
2318 if ( wxGetOsVersion() == wxOS_WINDOWS_9X
)
2320 wxLogError(_("Setting directory access times is not supported "
2321 "under this OS version"));
2326 flags
= FILE_FLAG_BACKUP_SEMANTICS
;
2330 path
= GetFullPath();
2334 wxFileHandle
fh(path
, wxFileHandle::Write
, flags
);
2337 if ( ::SetFileTime(fh
,
2338 dtCreate
? &ftCreate
: NULL
,
2339 dtAccess
? &ftAccess
: NULL
,
2340 dtMod
? &ftWrite
: NULL
) )
2345 #elif defined(__UNIX_LIKE__) || (defined(__DOS__) && defined(__WATCOMC__))
2346 wxUnusedVar(dtCreate
);
2348 if ( !dtAccess
&& !dtMod
)
2350 // can't modify the creation time anyhow, don't try
2354 // if dtAccess or dtMod is not specified, use the other one (which must be
2355 // non NULL because of the test above) for both times
2357 utm
.actime
= dtAccess
? dtAccess
->GetTicks() : dtMod
->GetTicks();
2358 utm
.modtime
= dtMod
? dtMod
->GetTicks() : dtAccess
->GetTicks();
2359 if ( utime(GetFullPath().fn_str(), &utm
) == 0 )
2363 #else // other platform
2364 wxUnusedVar(dtAccess
);
2366 wxUnusedVar(dtCreate
);
2369 wxLogSysError(_("Failed to modify file times for '%s'"),
2370 GetFullPath().c_str());
2375 bool wxFileName::Touch() const
2377 #if defined(__UNIX_LIKE__)
2378 // under Unix touching file is simple: just pass NULL to utime()
2379 if ( utime(GetFullPath().fn_str(), NULL
) == 0 )
2384 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
2387 #else // other platform
2388 wxDateTime dtNow
= wxDateTime::Now();
2390 return SetTimes(&dtNow
, &dtNow
, NULL
/* don't change create time */);
2394 bool wxFileName::GetTimes(wxDateTime
*dtAccess
,
2396 wxDateTime
*dtCreate
) const
2398 #if defined(__WIN32__)
2399 // we must use different methods for the files and directories under
2400 // Windows as CreateFile(GENERIC_READ) doesn't work for the directories and
2401 // CreateFile(FILE_FLAG_BACKUP_SEMANTICS) works -- but only under NT and
2404 FILETIME ftAccess
, ftCreate
, ftWrite
;
2407 // implemented in msw/dir.cpp
2408 extern bool wxGetDirectoryTimes(const wxString
& dirname
,
2409 FILETIME
*, FILETIME
*, FILETIME
*);
2411 // we should pass the path without the trailing separator to
2412 // wxGetDirectoryTimes()
2413 ok
= wxGetDirectoryTimes(GetPath(wxPATH_GET_VOLUME
),
2414 &ftAccess
, &ftCreate
, &ftWrite
);
2418 wxFileHandle
fh(GetFullPath(), wxFileHandle::Read
);
2421 ok
= ::GetFileTime(fh
,
2422 dtCreate
? &ftCreate
: NULL
,
2423 dtAccess
? &ftAccess
: NULL
,
2424 dtMod
? &ftWrite
: NULL
) != 0;
2435 ConvertFileTimeToWx(dtCreate
, ftCreate
);
2437 ConvertFileTimeToWx(dtAccess
, ftAccess
);
2439 ConvertFileTimeToWx(dtMod
, ftWrite
);
2443 #elif defined(__UNIX_LIKE__) || defined(__WXMAC__) || defined(__OS2__) || (defined(__DOS__) && defined(__WATCOMC__))
2444 // no need to test for IsDir() here
2446 if ( wxStat( GetFullPath().c_str(), &stBuf
) == 0 )
2449 dtAccess
->Set(stBuf
.st_atime
);
2451 dtMod
->Set(stBuf
.st_mtime
);
2453 dtCreate
->Set(stBuf
.st_ctime
);
2457 #else // other platform
2458 wxUnusedVar(dtAccess
);
2460 wxUnusedVar(dtCreate
);
2463 wxLogSysError(_("Failed to retrieve file times for '%s'"),
2464 GetFullPath().c_str());
2469 #endif // wxUSE_DATETIME
2472 // ----------------------------------------------------------------------------
2473 // file size functions
2474 // ----------------------------------------------------------------------------
2479 wxULongLong
wxFileName::GetSize(const wxString
&filename
)
2481 if (!wxFileExists(filename
))
2482 return wxInvalidSize
;
2484 #if defined(__WXPALMOS__)
2486 return wxInvalidSize
;
2487 #elif defined(__WIN32__)
2488 wxFileHandle
f(filename
, wxFileHandle::Read
);
2490 return wxInvalidSize
;
2492 DWORD lpFileSizeHigh
;
2493 DWORD ret
= GetFileSize(f
, &lpFileSizeHigh
);
2494 if ( ret
== INVALID_FILE_SIZE
&& ::GetLastError() != NO_ERROR
)
2495 return wxInvalidSize
;
2497 return wxULongLong(lpFileSizeHigh
, ret
);
2498 #else // ! __WIN32__
2500 #ifndef wxNEED_WX_UNISTD_H
2501 if (wxStat( filename
.fn_str() , &st
) != 0)
2503 if (wxStat( filename
, &st
) != 0)
2505 return wxInvalidSize
;
2506 return wxULongLong(st
.st_size
);
2511 wxString
wxFileName::GetHumanReadableSize(const wxULongLong
&bs
,
2512 const wxString
&nullsize
,
2515 static const double KILOBYTESIZE
= 1024.0;
2516 static const double MEGABYTESIZE
= 1024.0*KILOBYTESIZE
;
2517 static const double GIGABYTESIZE
= 1024.0*MEGABYTESIZE
;
2518 static const double TERABYTESIZE
= 1024.0*GIGABYTESIZE
;
2520 if (bs
== 0 || bs
== wxInvalidSize
)
2523 double bytesize
= bs
.ToDouble();
2524 if (bytesize
< KILOBYTESIZE
)
2525 return wxString::Format(_("%s B"), bs
.ToString().c_str());
2526 if (bytesize
< MEGABYTESIZE
)
2527 return wxString::Format(_("%.*f kB"), precision
, bytesize
/KILOBYTESIZE
);
2528 if (bytesize
< GIGABYTESIZE
)
2529 return wxString::Format(_("%.*f MB"), precision
, bytesize
/MEGABYTESIZE
);
2530 if (bytesize
< TERABYTESIZE
)
2531 return wxString::Format(_("%.*f GB"), precision
, bytesize
/GIGABYTESIZE
);
2533 return wxString::Format(_("%.*f TB"), precision
, bytesize
/TERABYTESIZE
);
2536 wxULongLong
wxFileName::GetSize() const
2538 return GetSize(GetFullPath());
2541 wxString
wxFileName::GetHumanReadableSize(const wxString
&failmsg
, int precision
) const
2543 return GetHumanReadableSize(GetSize(), failmsg
, precision
);
2546 #endif // wxUSE_LONGLONG
2548 // ----------------------------------------------------------------------------
2549 // Mac-specific functions
2550 // ----------------------------------------------------------------------------
2552 #if defined( __WXOSX_MAC__ ) && wxOSX_USE_CARBON
2557 class MacDefaultExtensionRecord
2560 MacDefaultExtensionRecord()
2566 // default copy ctor, assignment operator and dtor are ok
2568 MacDefaultExtensionRecord(const wxString
& ext
, OSType type
, OSType creator
)
2572 m_creator
= creator
;
2580 WX_DECLARE_OBJARRAY(MacDefaultExtensionRecord
, MacDefaultExtensionArray
);
2582 bool gMacDefaultExtensionsInited
= false;
2584 #include "wx/arrimpl.cpp"
2586 WX_DEFINE_EXPORTED_OBJARRAY(MacDefaultExtensionArray
);
2588 MacDefaultExtensionArray gMacDefaultExtensions
;
2590 // load the default extensions
2591 const MacDefaultExtensionRecord gDefaults
[] =
2593 MacDefaultExtensionRecord( "txt", 'TEXT', 'ttxt' ),
2594 MacDefaultExtensionRecord( "tif", 'TIFF', '****' ),
2595 MacDefaultExtensionRecord( "jpg", 'JPEG', '****' ),
2598 void MacEnsureDefaultExtensionsLoaded()
2600 if ( !gMacDefaultExtensionsInited
)
2602 // we could load the pc exchange prefs here too
2603 for ( size_t i
= 0 ; i
< WXSIZEOF( gDefaults
) ; ++i
)
2605 gMacDefaultExtensions
.Add( gDefaults
[i
] ) ;
2607 gMacDefaultExtensionsInited
= true;
2611 } // anonymous namespace
2613 bool wxFileName::MacSetTypeAndCreator( wxUint32 type
, wxUint32 creator
)
2616 FSCatalogInfo catInfo
;
2619 if ( wxMacPathToFSRef( GetFullPath() , &fsRef
) == noErr
)
2621 if ( FSGetCatalogInfo (&fsRef
, kFSCatInfoFinderInfo
, &catInfo
, NULL
, NULL
, NULL
) == noErr
)
2623 finfo
= (FileInfo
*)&catInfo
.finderInfo
;
2624 finfo
->fileType
= type
;
2625 finfo
->fileCreator
= creator
;
2626 FSSetCatalogInfo( &fsRef
, kFSCatInfoFinderInfo
, &catInfo
) ;
2633 bool wxFileName::MacGetTypeAndCreator( wxUint32
*type
, wxUint32
*creator
) const
2636 FSCatalogInfo catInfo
;
2639 if ( wxMacPathToFSRef( GetFullPath() , &fsRef
) == noErr
)
2641 if ( FSGetCatalogInfo (&fsRef
, kFSCatInfoFinderInfo
, &catInfo
, NULL
, NULL
, NULL
) == noErr
)
2643 finfo
= (FileInfo
*)&catInfo
.finderInfo
;
2644 *type
= finfo
->fileType
;
2645 *creator
= finfo
->fileCreator
;
2652 bool wxFileName::MacSetDefaultTypeAndCreator()
2654 wxUint32 type
, creator
;
2655 if ( wxFileName::MacFindDefaultTypeAndCreator(GetExt() , &type
,
2658 return MacSetTypeAndCreator( type
, creator
) ;
2663 bool wxFileName::MacFindDefaultTypeAndCreator( const wxString
& ext
, wxUint32
*type
, wxUint32
*creator
)
2665 MacEnsureDefaultExtensionsLoaded() ;
2666 wxString extl
= ext
.Lower() ;
2667 for( int i
= gMacDefaultExtensions
.Count() - 1 ; i
>= 0 ; --i
)
2669 if ( gMacDefaultExtensions
.Item(i
).m_ext
== extl
)
2671 *type
= gMacDefaultExtensions
.Item(i
).m_type
;
2672 *creator
= gMacDefaultExtensions
.Item(i
).m_creator
;
2679 void wxFileName::MacRegisterDefaultTypeAndCreator( const wxString
& ext
, wxUint32 type
, wxUint32 creator
)
2681 MacEnsureDefaultExtensionsLoaded();
2682 MacDefaultExtensionRecord
rec(ext
.Lower(), type
, creator
);
2683 gMacDefaultExtensions
.Add( rec
);
2686 #endif // defined( __WXOSX_MAC__ ) && wxOSX_USE_CARBON