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"
87 #if defined(__WIN32__) && defined(__MINGW32__)
88 #include "wx/msw/gccpriv.h"
92 #include "wx/msw/private.h"
95 #if defined(__WXMAC__)
96 #include "wx/osx/private.h" // includes mac headers
99 // utime() is POSIX so should normally be available on all Unices
101 #include <sys/types.h>
103 #include <sys/stat.h>
113 #include <sys/types.h>
115 #include <sys/stat.h>
126 #include <sys/utime.h>
127 #include <sys/stat.h>
138 #define MAX_PATH _MAX_PATH
143 extern const wxULongLong wxInvalidSize
= (unsigned)-1;
144 #endif // wxUSE_LONGLONG
147 // ----------------------------------------------------------------------------
149 // ----------------------------------------------------------------------------
151 // small helper class which opens and closes the file - we use it just to get
152 // a file handle for the given file name to pass it to some Win32 API function
153 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
164 wxFileHandle(const wxString
& filename
, OpenMode mode
, int flags
= 0)
166 m_hFile
= ::CreateFile
168 filename
.fn_str(), // name
169 mode
== Read
? GENERIC_READ
// access mask
171 FILE_SHARE_READ
| // sharing mode
172 FILE_SHARE_WRITE
, // (allow everything)
173 NULL
, // no secutity attr
174 OPEN_EXISTING
, // creation disposition
176 NULL
// no template file
179 if ( m_hFile
== INVALID_HANDLE_VALUE
)
182 wxLogSysError(_("Failed to open '%s' for reading"),
185 wxLogSysError(_("Failed to open '%s' for writing"),
192 if ( m_hFile
!= INVALID_HANDLE_VALUE
)
194 if ( !::CloseHandle(m_hFile
) )
196 wxLogSysError(_("Failed to close file handle"));
201 // return true only if the file could be opened successfully
202 bool IsOk() const { return m_hFile
!= INVALID_HANDLE_VALUE
; }
205 operator HANDLE() const { return m_hFile
; }
213 // ----------------------------------------------------------------------------
215 // ----------------------------------------------------------------------------
217 #if wxUSE_DATETIME && defined(__WIN32__) && !defined(__WXMICROWIN__)
219 // convert between wxDateTime and FILETIME which is a 64-bit value representing
220 // the number of 100-nanosecond intervals since January 1, 1601.
222 static void ConvertFileTimeToWx(wxDateTime
*dt
, const FILETIME
&ft
)
224 FILETIME ftcopy
= ft
;
226 if ( !::FileTimeToLocalFileTime(&ftcopy
, &ftLocal
) )
228 wxLogLastError(_T("FileTimeToLocalFileTime"));
232 if ( !::FileTimeToSystemTime(&ftLocal
, &st
) )
234 wxLogLastError(_T("FileTimeToSystemTime"));
237 dt
->Set(st
.wDay
, wxDateTime::Month(st
.wMonth
- 1), st
.wYear
,
238 st
.wHour
, st
.wMinute
, st
.wSecond
, st
.wMilliseconds
);
241 static void ConvertWxToFileTime(FILETIME
*ft
, const wxDateTime
& dt
)
244 st
.wDay
= dt
.GetDay();
245 st
.wMonth
= (WORD
)(dt
.GetMonth() + 1);
246 st
.wYear
= (WORD
)dt
.GetYear();
247 st
.wHour
= dt
.GetHour();
248 st
.wMinute
= dt
.GetMinute();
249 st
.wSecond
= dt
.GetSecond();
250 st
.wMilliseconds
= dt
.GetMillisecond();
253 if ( !::SystemTimeToFileTime(&st
, &ftLocal
) )
255 wxLogLastError(_T("SystemTimeToFileTime"));
258 if ( !::LocalFileTimeToFileTime(&ftLocal
, ft
) )
260 wxLogLastError(_T("LocalFileTimeToFileTime"));
264 #endif // wxUSE_DATETIME && __WIN32__
266 // return a string with the volume par
267 static wxString
wxGetVolumeString(const wxString
& volume
, wxPathFormat format
)
271 if ( !volume
.empty() )
273 format
= wxFileName::GetFormat(format
);
275 // Special Windows UNC paths hack, part 2: undo what we did in
276 // SplitPath() and make an UNC path if we have a drive which is not a
277 // single letter (hopefully the network shares can't be one letter only
278 // although I didn't find any authoritative docs on this)
279 if ( format
== wxPATH_DOS
&& volume
.length() > 1 )
281 path
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_DOS
<< volume
;
283 else if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
285 path
<< volume
<< wxFileName::GetVolumeSeparator(format
);
293 // return true if the format used is the DOS/Windows one and the string looks
295 static bool IsUNCPath(const wxString
& path
, wxPathFormat format
)
297 return format
== wxPATH_DOS
&&
298 path
.length() >= 4 && // "\\a" can't be a UNC path
299 path
[0u] == wxFILE_SEP_PATH_DOS
&&
300 path
[1u] == wxFILE_SEP_PATH_DOS
&&
301 path
[2u] != wxFILE_SEP_PATH_DOS
;
304 // ============================================================================
306 // ============================================================================
308 // ----------------------------------------------------------------------------
309 // wxFileName construction
310 // ----------------------------------------------------------------------------
312 void wxFileName::Assign( const wxFileName
&filepath
)
314 m_volume
= filepath
.GetVolume();
315 m_dirs
= filepath
.GetDirs();
316 m_name
= filepath
.GetName();
317 m_ext
= filepath
.GetExt();
318 m_relative
= filepath
.m_relative
;
319 m_hasExt
= filepath
.m_hasExt
;
322 void wxFileName::Assign(const wxString
& volume
,
323 const wxString
& path
,
324 const wxString
& name
,
329 // we should ignore paths which look like UNC shares because we already
330 // have the volume here and the UNC notation (\\server\path) is only valid
331 // for paths which don't start with a volume, so prevent SetPath() from
332 // recognizing "\\foo\bar" in "c:\\foo\bar" as an UNC path
334 // note also that this is a rather ugly way to do what we want (passing
335 // some kind of flag telling to ignore UNC paths to SetPath() would be
336 // better) but this is the safest thing to do to avoid breaking backwards
337 // compatibility in 2.8
338 if ( IsUNCPath(path
, format
) )
340 // remove one of the 2 leading backslashes to ensure that it's not
341 // recognized as an UNC path by SetPath()
342 wxString
pathNonUNC(path
, 1, wxString::npos
);
343 SetPath(pathNonUNC
, format
);
345 else // no UNC complications
347 SetPath(path
, format
);
357 void wxFileName::SetPath( const wxString
& pathOrig
, wxPathFormat format
)
361 if ( pathOrig
.empty() )
369 format
= GetFormat( format
);
371 // 0) deal with possible volume part first
374 SplitVolume(pathOrig
, &volume
, &path
, format
);
375 if ( !volume
.empty() )
382 // 1) Determine if the path is relative or absolute.
383 wxChar leadingChar
= path
[0u];
388 m_relative
= leadingChar
== wxT(':');
390 // We then remove a leading ":". The reason is in our
391 // storage form for relative paths:
392 // ":dir:file.txt" actually means "./dir/file.txt" in
393 // DOS notation and should get stored as
394 // (relative) (dir) (file.txt)
395 // "::dir:file.txt" actually means "../dir/file.txt"
396 // stored as (relative) (..) (dir) (file.txt)
397 // This is important only for the Mac as an empty dir
398 // actually means <UP>, whereas under DOS, double
399 // slashes can be ignored: "\\\\" is the same as "\\".
405 // TODO: what is the relative path format here?
410 wxFAIL_MSG( _T("Unknown path format") );
411 // !! Fall through !!
414 // the paths of the form "~" or "~username" are absolute
415 m_relative
= leadingChar
!= wxT('/') && leadingChar
!= _T('~');
419 m_relative
= !IsPathSeparator(leadingChar
, format
);
424 // 2) Break up the path into its members. If the original path
425 // was just "/" or "\\", m_dirs will be empty. We know from
426 // the m_relative field, if this means "nothing" or "root dir".
428 wxStringTokenizer
tn( path
, GetPathSeparators(format
) );
430 while ( tn
.HasMoreTokens() )
432 wxString token
= tn
.GetNextToken();
434 // Remove empty token under DOS and Unix, interpret them
438 if (format
== wxPATH_MAC
)
439 m_dirs
.Add( wxT("..") );
449 void wxFileName::Assign(const wxString
& fullpath
,
452 wxString volume
, path
, name
, ext
;
454 SplitPath(fullpath
, &volume
, &path
, &name
, &ext
, &hasExt
, format
);
456 Assign(volume
, path
, name
, ext
, hasExt
, format
);
459 void wxFileName::Assign(const wxString
& fullpathOrig
,
460 const wxString
& fullname
,
463 // always recognize fullpath as directory, even if it doesn't end with a
465 wxString fullpath
= fullpathOrig
;
466 if ( !fullpath
.empty() && !wxEndsWithPathSeparator(fullpath
) )
468 fullpath
+= GetPathSeparator(format
);
471 wxString volume
, path
, name
, ext
;
474 // do some consistency checks in debug mode: the name should be really just
475 // the filename and the path should be really just a path
477 wxString volDummy
, pathDummy
, nameDummy
, extDummy
;
479 SplitPath(fullname
, &volDummy
, &pathDummy
, &name
, &ext
, &hasExt
, format
);
481 wxASSERT_MSG( volDummy
.empty() && pathDummy
.empty(),
482 _T("the file name shouldn't contain the path") );
484 SplitPath(fullpath
, &volume
, &path
, &nameDummy
, &extDummy
, format
);
486 wxASSERT_MSG( nameDummy
.empty() && extDummy
.empty(),
487 _T("the path shouldn't contain file name nor extension") );
489 #else // !__WXDEBUG__
490 SplitPath(fullname
, NULL
/* no volume */, NULL
/* no path */,
491 &name
, &ext
, &hasExt
, format
);
492 SplitPath(fullpath
, &volume
, &path
, NULL
, NULL
, format
);
493 #endif // __WXDEBUG__/!__WXDEBUG__
495 Assign(volume
, path
, name
, ext
, hasExt
, format
);
498 void wxFileName::Assign(const wxString
& pathOrig
,
499 const wxString
& name
,
505 SplitVolume(pathOrig
, &volume
, &path
, format
);
507 Assign(volume
, path
, name
, ext
, format
);
510 void wxFileName::AssignDir(const wxString
& dir
, wxPathFormat format
)
512 Assign(dir
, wxEmptyString
, format
);
515 void wxFileName::Clear()
521 m_ext
= wxEmptyString
;
523 // we don't have any absolute path for now
531 wxFileName
wxFileName::FileName(const wxString
& file
, wxPathFormat format
)
533 return wxFileName(file
, format
);
537 wxFileName
wxFileName::DirName(const wxString
& dir
, wxPathFormat format
)
540 fn
.AssignDir(dir
, format
);
544 // ----------------------------------------------------------------------------
546 // ----------------------------------------------------------------------------
548 bool wxFileName::FileExists() const
550 return wxFileName::FileExists( GetFullPath() );
553 bool wxFileName::FileExists( const wxString
&file
)
555 return ::wxFileExists( file
);
558 bool wxFileName::DirExists() const
560 return wxFileName::DirExists( GetPath() );
563 bool wxFileName::DirExists( const wxString
&dir
)
565 return ::wxDirExists( dir
);
568 // ----------------------------------------------------------------------------
569 // CWD and HOME stuff
570 // ----------------------------------------------------------------------------
572 void wxFileName::AssignCwd(const wxString
& volume
)
574 AssignDir(wxFileName::GetCwd(volume
));
578 wxString
wxFileName::GetCwd(const wxString
& volume
)
580 // if we have the volume, we must get the current directory on this drive
581 // and to do this we have to chdir to this volume - at least under Windows,
582 // I don't know how to get the current drive on another volume elsewhere
585 if ( !volume
.empty() )
588 SetCwd(volume
+ GetVolumeSeparator());
591 wxString cwd
= ::wxGetCwd();
593 if ( !volume
.empty() )
601 bool wxFileName::SetCwd()
603 return wxFileName::SetCwd( GetPath() );
606 bool wxFileName::SetCwd( const wxString
&cwd
)
608 return ::wxSetWorkingDirectory( cwd
);
611 void wxFileName::AssignHomeDir()
613 AssignDir(wxFileName::GetHomeDir());
616 wxString
wxFileName::GetHomeDir()
618 return ::wxGetHomeDir();
622 // ----------------------------------------------------------------------------
623 // CreateTempFileName
624 // ----------------------------------------------------------------------------
626 #if wxUSE_FILE || wxUSE_FFILE
629 #if !defined wx_fdopen && defined HAVE_FDOPEN
630 #define wx_fdopen fdopen
633 // NB: GetTempFileName() under Windows creates the file, so using
634 // O_EXCL there would fail
636 #define wxOPEN_EXCL 0
638 #define wxOPEN_EXCL O_EXCL
642 #ifdef wxOpenOSFHandle
643 #define WX_HAVE_DELETE_ON_CLOSE
644 // On Windows create a file with the FILE_FLAGS_DELETE_ON_CLOSE flags.
646 static int wxOpenWithDeleteOnClose(const wxString
& filename
)
648 DWORD access
= GENERIC_READ
| GENERIC_WRITE
;
650 DWORD disposition
= OPEN_ALWAYS
;
652 DWORD attributes
= FILE_ATTRIBUTE_TEMPORARY
|
653 FILE_FLAG_DELETE_ON_CLOSE
;
655 HANDLE h
= ::CreateFile(filename
.fn_str(), access
, 0, NULL
,
656 disposition
, attributes
, NULL
);
658 return wxOpenOSFHandle(h
, wxO_BINARY
);
660 #endif // wxOpenOSFHandle
663 // Helper to open the file
665 static int wxTempOpen(const wxString
& path
, bool *deleteOnClose
)
667 #ifdef WX_HAVE_DELETE_ON_CLOSE
669 return wxOpenWithDeleteOnClose(path
);
672 *deleteOnClose
= false;
674 return wxOpen(path
, wxO_BINARY
| O_RDWR
| O_CREAT
| wxOPEN_EXCL
, 0600);
679 // Helper to open the file and attach it to the wxFFile
681 static bool wxTempOpen(wxFFile
*file
, const wxString
& path
, bool *deleteOnClose
)
684 *deleteOnClose
= false;
685 return file
->Open(path
, _T("w+b"));
687 int fd
= wxTempOpen(path
, deleteOnClose
);
690 file
->Attach(wx_fdopen(fd
, "w+b"));
691 return file
->IsOpened();
694 #endif // wxUSE_FFILE
698 #define WXFILEARGS(x, y) y
700 #define WXFILEARGS(x, y) x
702 #define WXFILEARGS(x, y) x, y
706 // Implementation of wxFileName::CreateTempFileName().
708 static wxString
wxCreateTempImpl(
709 const wxString
& prefix
,
710 WXFILEARGS(wxFile
*fileTemp
, wxFFile
*ffileTemp
),
711 bool *deleteOnClose
= NULL
)
713 #if wxUSE_FILE && wxUSE_FFILE
714 wxASSERT(fileTemp
== NULL
|| ffileTemp
== NULL
);
716 wxString path
, dir
, name
;
717 bool wantDeleteOnClose
= false;
721 // set the result to false initially
722 wantDeleteOnClose
= *deleteOnClose
;
723 *deleteOnClose
= false;
727 // easier if it alwasys points to something
728 deleteOnClose
= &wantDeleteOnClose
;
731 // use the directory specified by the prefix
732 wxFileName::SplitPath(prefix
, &dir
, &name
, NULL
/* extension */);
736 dir
= wxFileName::GetTempDir();
739 #if defined(__WXWINCE__)
740 path
= dir
+ wxT("\\") + name
;
742 while (wxFileName::FileExists(path
))
744 path
= dir
+ wxT("\\") + name
;
749 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
750 if ( !::GetTempFileName(dir
.fn_str(), name
.fn_str(), 0,
751 wxStringBuffer(path
, MAX_PATH
+ 1)) )
753 wxLogLastError(_T("GetTempFileName"));
761 if ( !wxEndsWithPathSeparator(dir
) &&
762 (name
.empty() || !wxIsPathSeparator(name
[0u])) )
764 path
+= wxFILE_SEP_PATH
;
769 #if defined(HAVE_MKSTEMP)
770 // scratch space for mkstemp()
771 path
+= _T("XXXXXX");
773 // we need to copy the path to the buffer in which mkstemp() can modify it
774 wxCharBuffer
buf(path
.fn_str());
776 // cast is safe because the string length doesn't change
777 int fdTemp
= mkstemp( (char*)(const char*) buf
);
780 // this might be not necessary as mkstemp() on most systems should have
781 // already done it but it doesn't hurt neither...
784 else // mkstemp() succeeded
786 path
= wxConvFile
.cMB2WX( (const char*) buf
);
789 // avoid leaking the fd
792 fileTemp
->Attach(fdTemp
);
801 ffileTemp
->Attach(wx_fdopen(fdTemp
, "r+b"));
803 ffileTemp
->Open(path
, _T("r+b"));
814 #else // !HAVE_MKSTEMP
818 path
+= _T("XXXXXX");
820 wxCharBuffer buf
= wxConvFile
.cWX2MB( path
);
821 if ( !mktemp( (char*)(const char*) buf
) )
827 path
= wxConvFile
.cMB2WX( (const char*) buf
);
829 #else // !HAVE_MKTEMP (includes __DOS__)
830 // generate the unique file name ourselves
831 #if !defined(__DOS__) && !defined(__PALMOS__) && (!defined(__MWERKS__) || defined(__DARWIN__) )
832 path
<< (unsigned int)getpid();
837 static const size_t numTries
= 1000;
838 for ( size_t n
= 0; n
< numTries
; n
++ )
840 // 3 hex digits is enough for numTries == 1000 < 4096
841 pathTry
= path
+ wxString::Format(_T("%.03x"), (unsigned int) n
);
842 if ( !wxFileName::FileExists(pathTry
) )
851 #endif // HAVE_MKTEMP/!HAVE_MKTEMP
853 #endif // HAVE_MKSTEMP/!HAVE_MKSTEMP
855 #endif // Windows/!Windows
859 wxLogSysError(_("Failed to create a temporary file name"));
865 // open the file - of course, there is a race condition here, this is
866 // why we always prefer using mkstemp()...
868 if ( fileTemp
&& !fileTemp
->IsOpened() )
870 *deleteOnClose
= wantDeleteOnClose
;
871 int fd
= wxTempOpen(path
, deleteOnClose
);
873 fileTemp
->Attach(fd
);
880 if ( ffileTemp
&& !ffileTemp
->IsOpened() )
882 *deleteOnClose
= wantDeleteOnClose
;
883 ok
= wxTempOpen(ffileTemp
, path
, deleteOnClose
);
889 // FIXME: If !ok here should we loop and try again with another
890 // file name? That is the standard recourse if open(O_EXCL)
891 // fails, though of course it should be protected against
892 // possible infinite looping too.
894 wxLogError(_("Failed to open temporary file."));
904 static bool wxCreateTempImpl(
905 const wxString
& prefix
,
906 WXFILEARGS(wxFile
*fileTemp
, wxFFile
*ffileTemp
),
909 bool deleteOnClose
= true;
911 *name
= wxCreateTempImpl(prefix
,
912 WXFILEARGS(fileTemp
, ffileTemp
),
915 bool ok
= !name
->empty();
920 else if (ok
&& wxRemoveFile(*name
))
928 static void wxAssignTempImpl(
930 const wxString
& prefix
,
931 WXFILEARGS(wxFile
*fileTemp
, wxFFile
*ffileTemp
))
934 tempname
= wxCreateTempImpl(prefix
, WXFILEARGS(fileTemp
, ffileTemp
));
936 if ( tempname
.empty() )
938 // error, failed to get temp file name
943 fn
->Assign(tempname
);
948 void wxFileName::AssignTempFileName(const wxString
& prefix
)
950 wxAssignTempImpl(this, prefix
, WXFILEARGS(NULL
, NULL
));
954 wxString
wxFileName::CreateTempFileName(const wxString
& prefix
)
956 return wxCreateTempImpl(prefix
, WXFILEARGS(NULL
, NULL
));
959 #endif // wxUSE_FILE || wxUSE_FFILE
964 wxString
wxCreateTempFileName(const wxString
& prefix
,
968 return wxCreateTempImpl(prefix
, WXFILEARGS(fileTemp
, NULL
), deleteOnClose
);
971 bool wxCreateTempFile(const wxString
& prefix
,
975 return wxCreateTempImpl(prefix
, WXFILEARGS(fileTemp
, NULL
), name
);
978 void wxFileName::AssignTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
980 wxAssignTempImpl(this, prefix
, WXFILEARGS(fileTemp
, NULL
));
985 wxFileName::CreateTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
987 return wxCreateTempFileName(prefix
, fileTemp
);
995 wxString
wxCreateTempFileName(const wxString
& prefix
,
999 return wxCreateTempImpl(prefix
, WXFILEARGS(NULL
, fileTemp
), deleteOnClose
);
1002 bool wxCreateTempFile(const wxString
& prefix
,
1006 return wxCreateTempImpl(prefix
, WXFILEARGS(NULL
, fileTemp
), name
);
1010 void wxFileName::AssignTempFileName(const wxString
& prefix
, wxFFile
*fileTemp
)
1012 wxAssignTempImpl(this, prefix
, WXFILEARGS(NULL
, fileTemp
));
1017 wxFileName::CreateTempFileName(const wxString
& prefix
, wxFFile
*fileTemp
)
1019 return wxCreateTempFileName(prefix
, fileTemp
);
1022 #endif // wxUSE_FFILE
1025 // ----------------------------------------------------------------------------
1026 // directory operations
1027 // ----------------------------------------------------------------------------
1029 // helper of GetTempDir(): check if the given directory exists and return it if
1030 // it does or an empty string otherwise
1034 wxString
CheckIfDirExists(const wxString
& dir
)
1036 return wxFileName::DirExists(dir
) ? dir
: wxString();
1039 } // anonymous namespace
1041 wxString
wxFileName::GetTempDir()
1043 // first try getting it from environment: this allows overriding the values
1044 // used by default if the user wants to create temporary files in another
1046 wxString dir
= CheckIfDirExists(wxGetenv("TMPDIR"));
1049 dir
= CheckIfDirExists(wxGetenv("TMP"));
1051 dir
= CheckIfDirExists(wxGetenv("TEMP"));
1054 // if no environment variables are set, use the system default
1057 #if defined(__WXWINCE__)
1058 dir
= CheckIfDirExists(wxT("\\temp"));
1059 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1060 if ( !::GetTempPath(MAX_PATH
, wxStringBuffer(dir
, MAX_PATH
+ 1)) )
1062 wxLogLastError(_T("GetTempPath"));
1064 #elif defined(__WXMAC__) && wxOSX_USE_CARBON
1065 dir
= wxMacFindFolder(short(kOnSystemDisk
), kTemporaryFolderType
, kCreateFolder
);
1066 #endif // systems with native way
1069 // fall back to hard coded value
1072 #ifdef __UNIX_LIKE__
1073 dir
= CheckIfDirExists("/tmp");
1075 #endif // __UNIX_LIKE__
1082 bool wxFileName::Mkdir( int perm
, int flags
)
1084 return wxFileName::Mkdir(GetPath(), perm
, flags
);
1087 bool wxFileName::Mkdir( const wxString
& dir
, int perm
, int flags
)
1089 if ( flags
& wxPATH_MKDIR_FULL
)
1091 // split the path in components
1092 wxFileName filename
;
1093 filename
.AssignDir(dir
);
1096 if ( filename
.HasVolume())
1098 currPath
<< wxGetVolumeString(filename
.GetVolume(), wxPATH_NATIVE
);
1101 wxArrayString dirs
= filename
.GetDirs();
1102 size_t count
= dirs
.GetCount();
1103 for ( size_t i
= 0; i
< count
; i
++ )
1105 if ( i
> 0 || filename
.IsAbsolute() )
1106 currPath
+= wxFILE_SEP_PATH
;
1107 currPath
+= dirs
[i
];
1109 if (!DirExists(currPath
))
1111 if (!wxMkdir(currPath
, perm
))
1113 // no need to try creating further directories
1123 return ::wxMkdir( dir
, perm
);
1126 bool wxFileName::Rmdir()
1128 return wxFileName::Rmdir( GetPath() );
1131 bool wxFileName::Rmdir( const wxString
&dir
)
1133 return ::wxRmdir( dir
);
1136 // ----------------------------------------------------------------------------
1137 // path normalization
1138 // ----------------------------------------------------------------------------
1140 bool wxFileName::Normalize(int flags
,
1141 const wxString
& cwd
,
1142 wxPathFormat format
)
1144 // deal with env vars renaming first as this may seriously change the path
1145 if ( flags
& wxPATH_NORM_ENV_VARS
)
1147 wxString pathOrig
= GetFullPath(format
);
1148 wxString path
= wxExpandEnvVars(pathOrig
);
1149 if ( path
!= pathOrig
)
1155 // the existing path components
1156 wxArrayString dirs
= GetDirs();
1158 // the path to prepend in front to make the path absolute
1161 format
= GetFormat(format
);
1163 // set up the directory to use for making the path absolute later
1164 if ( (flags
& wxPATH_NORM_ABSOLUTE
) && !IsAbsolute(format
) )
1168 curDir
.AssignCwd(GetVolume());
1170 else // cwd provided
1172 curDir
.AssignDir(cwd
);
1176 // handle ~ stuff under Unix only
1177 if ( (format
== wxPATH_UNIX
) && (flags
& wxPATH_NORM_TILDE
) )
1179 if ( !dirs
.IsEmpty() )
1181 wxString dir
= dirs
[0u];
1182 if ( !dir
.empty() && dir
[0u] == _T('~') )
1184 // to make the path absolute use the home directory
1185 curDir
.AssignDir(wxGetUserHome(dir
.c_str() + 1));
1187 // if we are expanding the tilde, then this path
1188 // *should* be already relative (since we checked for
1189 // the tilde only in the first char of the first dir);
1190 // if m_relative==false, it's because it was initialized
1191 // from a string which started with /~; in that case
1192 // we reach this point but then need m_relative=true
1193 // for relative->absolute expansion later
1201 // transform relative path into abs one
1202 if ( curDir
.IsOk() )
1204 // this path may be relative because it doesn't have the volume name
1205 // and still have m_relative=true; in this case we shouldn't modify
1206 // our directory components but just set the current volume
1207 if ( !HasVolume() && curDir
.HasVolume() )
1209 SetVolume(curDir
.GetVolume());
1213 // yes, it was the case - we don't need curDir then
1218 // finally, prepend curDir to the dirs array
1219 wxArrayString dirsNew
= curDir
.GetDirs();
1220 WX_PREPEND_ARRAY(dirs
, dirsNew
);
1222 // if we used e.g. tilde expansion previously and wxGetUserHome didn't
1223 // return for some reason an absolute path, then curDir maybe not be absolute!
1224 if ( curDir
.IsAbsolute(format
) )
1226 // we have prepended an absolute path and thus we are now an absolute
1230 // else if (flags & wxPATH_NORM_ABSOLUTE):
1231 // should we warn the user that we didn't manage to make the path absolute?
1234 // now deal with ".", ".." and the rest
1236 size_t count
= dirs
.GetCount();
1237 for ( size_t n
= 0; n
< count
; n
++ )
1239 wxString dir
= dirs
[n
];
1241 if ( flags
& wxPATH_NORM_DOTS
)
1243 if ( dir
== wxT(".") )
1249 if ( dir
== wxT("..") )
1251 if ( m_dirs
.IsEmpty() )
1253 wxLogError(_("The path '%s' contains too many \"..\"!"),
1254 GetFullPath().c_str());
1258 m_dirs
.RemoveAt(m_dirs
.GetCount() - 1);
1266 #if defined(__WIN32__) && !defined(__WXWINCE__) && wxUSE_OLE
1267 if ( (flags
& wxPATH_NORM_SHORTCUT
) )
1270 if (GetShortcutTarget(GetFullPath(format
), filename
))
1278 #if defined(__WIN32__)
1279 if ( (flags
& wxPATH_NORM_LONG
) && (format
== wxPATH_DOS
) )
1281 Assign(GetLongPath());
1285 // Change case (this should be kept at the end of the function, to ensure
1286 // that the path doesn't change any more after we normalize its case)
1287 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
1289 m_volume
.MakeLower();
1293 // directory entries must be made lower case as well
1294 count
= m_dirs
.GetCount();
1295 for ( size_t i
= 0; i
< count
; i
++ )
1297 m_dirs
[i
].MakeLower();
1305 bool wxFileName::ReplaceEnvVariable(const wxString
& envname
,
1306 const wxString
& replacementFmtString
,
1307 wxPathFormat format
)
1309 // look into stringForm for the contents of the given environment variable
1311 if (envname
.empty() ||
1312 !wxGetEnv(envname
, &val
))
1317 wxString stringForm
= GetPath(wxPATH_GET_VOLUME
, format
);
1318 // do not touch the file name and the extension
1320 wxString replacement
= wxString::Format(replacementFmtString
, envname
);
1321 stringForm
.Replace(val
, replacement
);
1323 // Now assign ourselves the modified path:
1324 Assign(stringForm
, GetFullName(), format
);
1330 bool wxFileName::ReplaceHomeDir(wxPathFormat format
)
1332 wxString homedir
= wxGetHomeDir();
1333 if (homedir
.empty())
1336 wxString stringForm
= GetPath(wxPATH_GET_VOLUME
, format
);
1337 // do not touch the file name and the extension
1339 stringForm
.Replace(homedir
, "~");
1341 // Now assign ourselves the modified path:
1342 Assign(stringForm
, GetFullName(), format
);
1347 // ----------------------------------------------------------------------------
1348 // get the shortcut target
1349 // ----------------------------------------------------------------------------
1351 // WinCE (3) doesn't have CLSID_ShellLink, IID_IShellLink definitions.
1352 // The .lnk file is a plain text file so it should be easy to
1353 // make it work. Hint from Google Groups:
1354 // "If you open up a lnk file, you'll see a
1355 // number, followed by a pound sign (#), followed by more text. The
1356 // number is the number of characters that follows the pound sign. The
1357 // characters after the pound sign are the command line (which _can_
1358 // include arguments) to be executed. Any path (e.g. \windows\program
1359 // files\myapp.exe) that includes spaces needs to be enclosed in
1360 // quotation marks."
1362 #if defined(__WIN32__) && !defined(__WXWINCE__) && wxUSE_OLE
1363 // The following lines are necessary under WinCE
1364 // #include "wx/msw/private.h"
1365 // #include <ole2.h>
1367 #if defined(__WXWINCE__)
1368 #include <shlguid.h>
1371 bool wxFileName::GetShortcutTarget(const wxString
& shortcutPath
,
1372 wxString
& targetFilename
,
1373 wxString
* arguments
)
1375 wxString path
, file
, ext
;
1376 wxFileName::SplitPath(shortcutPath
, & path
, & file
, & ext
);
1380 bool success
= false;
1382 // Assume it's not a shortcut if it doesn't end with lnk
1383 if (ext
.CmpNoCase(wxT("lnk"))!=0)
1386 // create a ShellLink object
1387 hres
= CoCreateInstance(CLSID_ShellLink
, NULL
, CLSCTX_INPROC_SERVER
,
1388 IID_IShellLink
, (LPVOID
*) &psl
);
1390 if (SUCCEEDED(hres
))
1393 hres
= psl
->QueryInterface( IID_IPersistFile
, (LPVOID
*) &ppf
);
1394 if (SUCCEEDED(hres
))
1396 WCHAR wsz
[MAX_PATH
];
1398 MultiByteToWideChar(CP_ACP
, MB_PRECOMPOSED
, shortcutPath
.mb_str(), -1, wsz
,
1401 hres
= ppf
->Load(wsz
, 0);
1404 if (SUCCEEDED(hres
))
1407 // Wrong prototype in early versions
1408 #if defined(__MINGW32__) && !wxCHECK_W32API_VERSION(2, 2)
1409 psl
->GetPath((CHAR
*) buf
, 2048, NULL
, SLGP_UNCPRIORITY
);
1411 psl
->GetPath(buf
, 2048, NULL
, SLGP_UNCPRIORITY
);
1413 targetFilename
= wxString(buf
);
1414 success
= (shortcutPath
!= targetFilename
);
1416 psl
->GetArguments(buf
, 2048);
1418 if (!args
.empty() && arguments
)
1430 #endif // __WIN32__ && !__WXWINCE__
1433 // ----------------------------------------------------------------------------
1434 // absolute/relative paths
1435 // ----------------------------------------------------------------------------
1437 bool wxFileName::IsAbsolute(wxPathFormat format
) const
1439 // if our path doesn't start with a path separator, it's not an absolute
1444 if ( !GetVolumeSeparator(format
).empty() )
1446 // this format has volumes and an absolute path must have one, it's not
1447 // enough to have the full path to bean absolute file under Windows
1448 if ( GetVolume().empty() )
1455 bool wxFileName::MakeRelativeTo(const wxString
& pathBase
, wxPathFormat format
)
1457 wxFileName fnBase
= wxFileName::DirName(pathBase
, format
);
1459 // get cwd only once - small time saving
1460 wxString cwd
= wxGetCwd();
1461 Normalize(wxPATH_NORM_ALL
& ~wxPATH_NORM_CASE
, cwd
, format
);
1462 fnBase
.Normalize(wxPATH_NORM_ALL
& ~wxPATH_NORM_CASE
, cwd
, format
);
1464 bool withCase
= IsCaseSensitive(format
);
1466 // we can't do anything if the files live on different volumes
1467 if ( !GetVolume().IsSameAs(fnBase
.GetVolume(), withCase
) )
1473 // same drive, so we don't need our volume
1476 // remove common directories starting at the top
1477 while ( !m_dirs
.IsEmpty() && !fnBase
.m_dirs
.IsEmpty() &&
1478 m_dirs
[0u].IsSameAs(fnBase
.m_dirs
[0u], withCase
) )
1481 fnBase
.m_dirs
.RemoveAt(0);
1484 // add as many ".." as needed
1485 size_t count
= fnBase
.m_dirs
.GetCount();
1486 for ( size_t i
= 0; i
< count
; i
++ )
1488 m_dirs
.Insert(wxT(".."), 0u);
1491 if ( format
== wxPATH_UNIX
|| format
== wxPATH_DOS
)
1493 // a directory made relative with respect to itself is '.' under Unix
1494 // and DOS, by definition (but we don't have to insert "./" for the
1496 if ( m_dirs
.IsEmpty() && IsDir() )
1498 m_dirs
.Add(_T('.'));
1508 // ----------------------------------------------------------------------------
1509 // filename kind tests
1510 // ----------------------------------------------------------------------------
1512 bool wxFileName::SameAs(const wxFileName
& filepath
, wxPathFormat format
) const
1514 wxFileName fn1
= *this,
1517 // get cwd only once - small time saving
1518 wxString cwd
= wxGetCwd();
1519 fn1
.Normalize(wxPATH_NORM_ALL
| wxPATH_NORM_CASE
, cwd
, format
);
1520 fn2
.Normalize(wxPATH_NORM_ALL
| wxPATH_NORM_CASE
, cwd
, format
);
1522 if ( fn1
.GetFullPath() == fn2
.GetFullPath() )
1525 // TODO: compare inodes for Unix, this works even when filenames are
1526 // different but files are the same (symlinks) (VZ)
1532 bool wxFileName::IsCaseSensitive( wxPathFormat format
)
1534 // only Unix filenames are truely case-sensitive
1535 return GetFormat(format
) == wxPATH_UNIX
;
1539 wxString
wxFileName::GetForbiddenChars(wxPathFormat format
)
1541 // Inits to forbidden characters that are common to (almost) all platforms.
1542 wxString strForbiddenChars
= wxT("*?");
1544 // If asserts, wxPathFormat has been changed. In case of a new path format
1545 // addition, the following code might have to be updated.
1546 wxCOMPILE_TIME_ASSERT(wxPATH_MAX
== 5, wxPathFormatChanged
);
1547 switch ( GetFormat(format
) )
1550 wxFAIL_MSG( wxT("Unknown path format") );
1551 // !! Fall through !!
1557 // On a Mac even names with * and ? are allowed (Tested with OS
1558 // 9.2.1 and OS X 10.2.5)
1559 strForbiddenChars
= wxEmptyString
;
1563 strForbiddenChars
+= wxT("\\/:\"<>|");
1570 return strForbiddenChars
;
1574 wxString
wxFileName::GetVolumeSeparator(wxPathFormat
WXUNUSED_IN_WINCE(format
))
1577 return wxEmptyString
;
1581 if ( (GetFormat(format
) == wxPATH_DOS
) ||
1582 (GetFormat(format
) == wxPATH_VMS
) )
1584 sepVol
= wxFILE_SEP_DSK
;
1593 wxString
wxFileName::GetPathSeparators(wxPathFormat format
)
1596 switch ( GetFormat(format
) )
1599 // accept both as native APIs do but put the native one first as
1600 // this is the one we use in GetFullPath()
1601 seps
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_UNIX
;
1605 wxFAIL_MSG( _T("Unknown wxPATH_XXX style") );
1609 seps
= wxFILE_SEP_PATH_UNIX
;
1613 seps
= wxFILE_SEP_PATH_MAC
;
1617 seps
= wxFILE_SEP_PATH_VMS
;
1625 wxString
wxFileName::GetPathTerminators(wxPathFormat format
)
1627 format
= GetFormat(format
);
1629 // under VMS the end of the path is ']', not the path separator used to
1630 // separate the components
1631 return format
== wxPATH_VMS
? wxString(_T(']')) : GetPathSeparators(format
);
1635 bool wxFileName::IsPathSeparator(wxChar ch
, wxPathFormat format
)
1637 // wxString::Find() doesn't work as expected with NUL - it will always find
1638 // it, so test for it separately
1639 return ch
!= _T('\0') && GetPathSeparators(format
).Find(ch
) != wxNOT_FOUND
;
1642 // ----------------------------------------------------------------------------
1643 // path components manipulation
1644 // ----------------------------------------------------------------------------
1646 /* static */ bool wxFileName::IsValidDirComponent(const wxString
& dir
)
1650 wxFAIL_MSG( _T("empty directory passed to wxFileName::InsertDir()") );
1655 const size_t len
= dir
.length();
1656 for ( size_t n
= 0; n
< len
; n
++ )
1658 if ( dir
[n
] == GetVolumeSeparator() || IsPathSeparator(dir
[n
]) )
1660 wxFAIL_MSG( _T("invalid directory component in wxFileName") );
1669 void wxFileName::AppendDir( const wxString
& dir
)
1671 if ( IsValidDirComponent(dir
) )
1675 void wxFileName::PrependDir( const wxString
& dir
)
1680 void wxFileName::InsertDir(size_t before
, const wxString
& dir
)
1682 if ( IsValidDirComponent(dir
) )
1683 m_dirs
.Insert(dir
, before
);
1686 void wxFileName::RemoveDir(size_t pos
)
1688 m_dirs
.RemoveAt(pos
);
1691 // ----------------------------------------------------------------------------
1693 // ----------------------------------------------------------------------------
1695 void wxFileName::SetFullName(const wxString
& fullname
)
1697 SplitPath(fullname
, NULL
/* no volume */, NULL
/* no path */,
1698 &m_name
, &m_ext
, &m_hasExt
);
1701 wxString
wxFileName::GetFullName() const
1703 wxString fullname
= m_name
;
1706 fullname
<< wxFILE_SEP_EXT
<< m_ext
;
1712 wxString
wxFileName::GetPath( int flags
, wxPathFormat format
) const
1714 format
= GetFormat( format
);
1718 // return the volume with the path as well if requested
1719 if ( flags
& wxPATH_GET_VOLUME
)
1721 fullpath
+= wxGetVolumeString(GetVolume(), format
);
1724 // the leading character
1729 fullpath
+= wxFILE_SEP_PATH_MAC
;
1734 fullpath
+= wxFILE_SEP_PATH_DOS
;
1738 wxFAIL_MSG( wxT("Unknown path format") );
1744 // normally the absolute file names start with a slash
1745 // with one exception: the ones like "~/foo.bar" don't
1747 if ( m_dirs
.IsEmpty() || m_dirs
[0u] != _T('~') )
1749 fullpath
+= wxFILE_SEP_PATH_UNIX
;
1755 // no leading character here but use this place to unset
1756 // wxPATH_GET_SEPARATOR flag: under VMS it doesn't make sense
1757 // as, if I understand correctly, there should never be a dot
1758 // before the closing bracket
1759 flags
&= ~wxPATH_GET_SEPARATOR
;
1762 if ( m_dirs
.empty() )
1764 // there is nothing more
1768 // then concatenate all the path components using the path separator
1769 if ( format
== wxPATH_VMS
)
1771 fullpath
+= wxT('[');
1774 const size_t dirCount
= m_dirs
.GetCount();
1775 for ( size_t i
= 0; i
< dirCount
; i
++ )
1780 if ( m_dirs
[i
] == wxT(".") )
1782 // skip appending ':', this shouldn't be done in this
1783 // case as "::" is interpreted as ".." under Unix
1787 // convert back from ".." to nothing
1788 if ( !m_dirs
[i
].IsSameAs(wxT("..")) )
1789 fullpath
+= m_dirs
[i
];
1793 wxFAIL_MSG( wxT("Unexpected path format") );
1794 // still fall through
1798 fullpath
+= m_dirs
[i
];
1802 // TODO: What to do with ".." under VMS
1804 // convert back from ".." to nothing
1805 if ( !m_dirs
[i
].IsSameAs(wxT("..")) )
1806 fullpath
+= m_dirs
[i
];
1810 if ( (flags
& wxPATH_GET_SEPARATOR
) || (i
!= dirCount
- 1) )
1811 fullpath
+= GetPathSeparator(format
);
1814 if ( format
== wxPATH_VMS
)
1816 fullpath
+= wxT(']');
1822 wxString
wxFileName::GetFullPath( wxPathFormat format
) const
1824 // we already have a function to get the path
1825 wxString fullpath
= GetPath(wxPATH_GET_VOLUME
| wxPATH_GET_SEPARATOR
,
1828 // now just add the file name and extension to it
1829 fullpath
+= GetFullName();
1834 // Return the short form of the path (returns identity on non-Windows platforms)
1835 wxString
wxFileName::GetShortPath() const
1837 wxString
path(GetFullPath());
1839 #if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
1840 DWORD sz
= ::GetShortPathName(path
.fn_str(), NULL
, 0);
1844 if ( ::GetShortPathName
1847 wxStringBuffer(pathOut
, sz
),
1859 // Return the long form of the path (returns identity on non-Windows platforms)
1860 wxString
wxFileName::GetLongPath() const
1863 path
= GetFullPath();
1865 #if defined(__WIN32__) && !defined(__WXWINCE__) && !defined(__WXMICROWIN__)
1867 #if wxUSE_DYNLIB_CLASS
1868 typedef DWORD (WINAPI
*GET_LONG_PATH_NAME
)(const wxChar
*, wxChar
*, DWORD
);
1870 // this is MT-safe as in the worst case we're going to resolve the function
1871 // twice -- but as the result is the same in both threads, it's ok
1872 static GET_LONG_PATH_NAME s_pfnGetLongPathName
= NULL
;
1873 if ( !s_pfnGetLongPathName
)
1875 static bool s_triedToLoad
= false;
1877 if ( !s_triedToLoad
)
1879 s_triedToLoad
= true;
1881 wxDynamicLibrary
dllKernel(_T("kernel32"));
1883 const wxChar
* GetLongPathName
= _T("GetLongPathName")
1888 #endif // Unicode/ANSI
1890 if ( dllKernel
.HasSymbol(GetLongPathName
) )
1892 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
)
1893 dllKernel
.GetSymbol(GetLongPathName
);
1896 // note that kernel32.dll can be unloaded, it stays in memory
1897 // anyhow as all Win32 programs link to it and so it's safe to call
1898 // GetLongPathName() even after unloading it
1902 if ( s_pfnGetLongPathName
)
1904 DWORD dwSize
= (*s_pfnGetLongPathName
)(path
.fn_str(), NULL
, 0);
1907 if ( (*s_pfnGetLongPathName
)
1910 wxStringBuffer(pathOut
, dwSize
),
1918 #endif // wxUSE_DYNLIB_CLASS
1920 // The OS didn't support GetLongPathName, or some other error.
1921 // We need to call FindFirstFile on each component in turn.
1923 WIN32_FIND_DATA findFileData
;
1927 pathOut
= GetVolume() +
1928 GetVolumeSeparator(wxPATH_DOS
) +
1929 GetPathSeparator(wxPATH_DOS
);
1931 pathOut
= wxEmptyString
;
1933 wxArrayString dirs
= GetDirs();
1934 dirs
.Add(GetFullName());
1938 size_t count
= dirs
.GetCount();
1939 for ( size_t i
= 0; i
< count
; i
++ )
1941 const wxString
& dir
= dirs
[i
];
1943 // We're using pathOut to collect the long-name path, but using a
1944 // temporary for appending the last path component which may be
1946 tmpPath
= pathOut
+ dir
;
1948 // We must not process "." or ".." here as they would be (unexpectedly)
1949 // replaced by the corresponding directory names so just leave them
1952 // And we can't pass a drive and root dir to FindFirstFile (VZ: why?)
1953 if ( tmpPath
.empty() || dir
== '.' || dir
== ".." ||
1954 tmpPath
.Last() == GetVolumeSeparator(wxPATH_DOS
) )
1956 tmpPath
+= wxFILE_SEP_PATH
;
1961 hFind
= ::FindFirstFile(tmpPath
.fn_str(), &findFileData
);
1962 if (hFind
== INVALID_HANDLE_VALUE
)
1964 // Error: most likely reason is that path doesn't exist, so
1965 // append any unprocessed parts and return
1966 for ( i
+= 1; i
< count
; i
++ )
1967 tmpPath
+= wxFILE_SEP_PATH
+ dirs
[i
];
1972 pathOut
+= findFileData
.cFileName
;
1973 if ( (i
< (count
-1)) )
1974 pathOut
+= wxFILE_SEP_PATH
;
1980 #endif // Win32/!Win32
1985 wxPathFormat
wxFileName::GetFormat( wxPathFormat format
)
1987 if (format
== wxPATH_NATIVE
)
1989 #if defined(__WXMSW__) || defined(__OS2__) || defined(__DOS__)
1990 format
= wxPATH_DOS
;
1991 #elif defined(__VMS)
1992 format
= wxPATH_VMS
;
1994 format
= wxPATH_UNIX
;
2000 #ifdef wxHAS_FILESYSTEM_VOLUMES
2003 wxString
wxFileName::GetVolumeString(char drive
, int flags
)
2005 wxASSERT_MSG( !(flags
& ~wxPATH_GET_SEPARATOR
), "invalid flag specified" );
2007 wxString
vol(drive
);
2008 vol
+= wxFILE_SEP_DSK
;
2009 if ( flags
& wxPATH_GET_SEPARATOR
)
2010 vol
+= wxFILE_SEP_PATH
;
2015 #endif // wxHAS_FILESYSTEM_VOLUMES
2017 // ----------------------------------------------------------------------------
2018 // path splitting function
2019 // ----------------------------------------------------------------------------
2023 wxFileName::SplitVolume(const wxString
& fullpathWithVolume
,
2024 wxString
*pstrVolume
,
2026 wxPathFormat format
)
2028 format
= GetFormat(format
);
2030 wxString fullpath
= fullpathWithVolume
;
2032 // special Windows UNC paths hack: transform \\share\path into share:path
2033 if ( IsUNCPath(fullpath
, format
) )
2035 fullpath
.erase(0, 2);
2037 size_t posFirstSlash
=
2038 fullpath
.find_first_of(GetPathTerminators(format
));
2039 if ( posFirstSlash
!= wxString::npos
)
2041 fullpath
[posFirstSlash
] = wxFILE_SEP_DSK
;
2043 // UNC paths are always absolute, right? (FIXME)
2044 fullpath
.insert(posFirstSlash
+ 1, 1, wxFILE_SEP_PATH_DOS
);
2048 // We separate the volume here
2049 if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
2051 wxString sepVol
= GetVolumeSeparator(format
);
2053 size_t posFirstColon
= fullpath
.find_first_of(sepVol
);
2054 if ( posFirstColon
!= wxString::npos
)
2058 *pstrVolume
= fullpath
.Left(posFirstColon
);
2061 // remove the volume name and the separator from the full path
2062 fullpath
.erase(0, posFirstColon
+ sepVol
.length());
2067 *pstrPath
= fullpath
;
2071 void wxFileName::SplitPath(const wxString
& fullpathWithVolume
,
2072 wxString
*pstrVolume
,
2077 wxPathFormat format
)
2079 format
= GetFormat(format
);
2082 SplitVolume(fullpathWithVolume
, pstrVolume
, &fullpath
, format
);
2084 // find the positions of the last dot and last path separator in the path
2085 size_t posLastDot
= fullpath
.find_last_of(wxFILE_SEP_EXT
);
2086 size_t posLastSlash
= fullpath
.find_last_of(GetPathTerminators(format
));
2088 // check whether this dot occurs at the very beginning of a path component
2089 if ( (posLastDot
!= wxString::npos
) &&
2091 IsPathSeparator(fullpath
[posLastDot
- 1]) ||
2092 (format
== wxPATH_VMS
&& fullpath
[posLastDot
- 1] == _T(']'))) )
2094 // dot may be (and commonly -- at least under Unix -- is) the first
2095 // character of the filename, don't treat the entire filename as
2096 // extension in this case
2097 posLastDot
= wxString::npos
;
2100 // if we do have a dot and a slash, check that the dot is in the name part
2101 if ( (posLastDot
!= wxString::npos
) &&
2102 (posLastSlash
!= wxString::npos
) &&
2103 (posLastDot
< posLastSlash
) )
2105 // the dot is part of the path, not the start of the extension
2106 posLastDot
= wxString::npos
;
2109 // now fill in the variables provided by user
2112 if ( posLastSlash
== wxString::npos
)
2119 // take everything up to the path separator but take care to make
2120 // the path equal to something like '/', not empty, for the files
2121 // immediately under root directory
2122 size_t len
= posLastSlash
;
2124 // this rule does not apply to mac since we do not start with colons (sep)
2125 // except for relative paths
2126 if ( !len
&& format
!= wxPATH_MAC
)
2129 *pstrPath
= fullpath
.Left(len
);
2131 // special VMS hack: remove the initial bracket
2132 if ( format
== wxPATH_VMS
)
2134 if ( (*pstrPath
)[0u] == _T('[') )
2135 pstrPath
->erase(0, 1);
2142 // take all characters starting from the one after the last slash and
2143 // up to, but excluding, the last dot
2144 size_t nStart
= posLastSlash
== wxString::npos
? 0 : posLastSlash
+ 1;
2146 if ( posLastDot
== wxString::npos
)
2148 // take all until the end
2149 count
= wxString::npos
;
2151 else if ( posLastSlash
== wxString::npos
)
2155 else // have both dot and slash
2157 count
= posLastDot
- posLastSlash
- 1;
2160 *pstrName
= fullpath
.Mid(nStart
, count
);
2163 // finally deal with the extension here: we have an added complication that
2164 // extension may be empty (but present) as in "foo." where trailing dot
2165 // indicates the empty extension at the end -- and hence we must remember
2166 // that we have it independently of pstrExt
2167 if ( posLastDot
== wxString::npos
)
2177 // take everything after the dot
2179 *pstrExt
= fullpath
.Mid(posLastDot
+ 1);
2186 void wxFileName::SplitPath(const wxString
& fullpath
,
2190 wxPathFormat format
)
2193 SplitPath(fullpath
, &volume
, path
, name
, ext
, format
);
2197 path
->Prepend(wxGetVolumeString(volume
, format
));
2201 // ----------------------------------------------------------------------------
2203 // ----------------------------------------------------------------------------
2207 bool wxFileName::SetTimes(const wxDateTime
*dtAccess
,
2208 const wxDateTime
*dtMod
,
2209 const wxDateTime
*dtCreate
)
2211 #if defined(__WIN32__)
2212 FILETIME ftAccess
, ftCreate
, ftWrite
;
2215 ConvertWxToFileTime(&ftCreate
, *dtCreate
);
2217 ConvertWxToFileTime(&ftAccess
, *dtAccess
);
2219 ConvertWxToFileTime(&ftWrite
, *dtMod
);
2225 if ( wxGetOsVersion() == wxOS_WINDOWS_9X
)
2227 wxLogError(_("Setting directory access times is not supported "
2228 "under this OS version"));
2233 flags
= FILE_FLAG_BACKUP_SEMANTICS
;
2237 path
= GetFullPath();
2241 wxFileHandle
fh(path
, wxFileHandle::Write
, flags
);
2244 if ( ::SetFileTime(fh
,
2245 dtCreate
? &ftCreate
: NULL
,
2246 dtAccess
? &ftAccess
: NULL
,
2247 dtMod
? &ftWrite
: NULL
) )
2252 #elif defined(__UNIX_LIKE__) || (defined(__DOS__) && defined(__WATCOMC__))
2253 wxUnusedVar(dtCreate
);
2255 if ( !dtAccess
&& !dtMod
)
2257 // can't modify the creation time anyhow, don't try
2261 // if dtAccess or dtMod is not specified, use the other one (which must be
2262 // non NULL because of the test above) for both times
2264 utm
.actime
= dtAccess
? dtAccess
->GetTicks() : dtMod
->GetTicks();
2265 utm
.modtime
= dtMod
? dtMod
->GetTicks() : dtAccess
->GetTicks();
2266 if ( utime(GetFullPath().fn_str(), &utm
) == 0 )
2270 #else // other platform
2271 wxUnusedVar(dtAccess
);
2273 wxUnusedVar(dtCreate
);
2276 wxLogSysError(_("Failed to modify file times for '%s'"),
2277 GetFullPath().c_str());
2282 bool wxFileName::Touch()
2284 #if defined(__UNIX_LIKE__)
2285 // under Unix touching file is simple: just pass NULL to utime()
2286 if ( utime(GetFullPath().fn_str(), NULL
) == 0 )
2291 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
2294 #else // other platform
2295 wxDateTime dtNow
= wxDateTime::Now();
2297 return SetTimes(&dtNow
, &dtNow
, NULL
/* don't change create time */);
2301 bool wxFileName::GetTimes(wxDateTime
*dtAccess
,
2303 wxDateTime
*dtCreate
) const
2305 #if defined(__WIN32__)
2306 // we must use different methods for the files and directories under
2307 // Windows as CreateFile(GENERIC_READ) doesn't work for the directories and
2308 // CreateFile(FILE_FLAG_BACKUP_SEMANTICS) works -- but only under NT and
2311 FILETIME ftAccess
, ftCreate
, ftWrite
;
2314 // implemented in msw/dir.cpp
2315 extern bool wxGetDirectoryTimes(const wxString
& dirname
,
2316 FILETIME
*, FILETIME
*, FILETIME
*);
2318 // we should pass the path without the trailing separator to
2319 // wxGetDirectoryTimes()
2320 ok
= wxGetDirectoryTimes(GetPath(wxPATH_GET_VOLUME
),
2321 &ftAccess
, &ftCreate
, &ftWrite
);
2325 wxFileHandle
fh(GetFullPath(), wxFileHandle::Read
);
2328 ok
= ::GetFileTime(fh
,
2329 dtCreate
? &ftCreate
: NULL
,
2330 dtAccess
? &ftAccess
: NULL
,
2331 dtMod
? &ftWrite
: NULL
) != 0;
2342 ConvertFileTimeToWx(dtCreate
, ftCreate
);
2344 ConvertFileTimeToWx(dtAccess
, ftAccess
);
2346 ConvertFileTimeToWx(dtMod
, ftWrite
);
2350 #elif defined(__UNIX_LIKE__) || defined(__WXMAC__) || defined(__OS2__) || (defined(__DOS__) && defined(__WATCOMC__))
2351 // no need to test for IsDir() here
2353 if ( wxStat( GetFullPath().c_str(), &stBuf
) == 0 )
2356 dtAccess
->Set(stBuf
.st_atime
);
2358 dtMod
->Set(stBuf
.st_mtime
);
2360 dtCreate
->Set(stBuf
.st_ctime
);
2364 #else // other platform
2365 wxUnusedVar(dtAccess
);
2367 wxUnusedVar(dtCreate
);
2370 wxLogSysError(_("Failed to retrieve file times for '%s'"),
2371 GetFullPath().c_str());
2376 #endif // wxUSE_DATETIME
2379 // ----------------------------------------------------------------------------
2380 // file size functions
2381 // ----------------------------------------------------------------------------
2386 wxULongLong
wxFileName::GetSize(const wxString
&filename
)
2388 if (!wxFileExists(filename
))
2389 return wxInvalidSize
;
2391 #if defined(__WXPALMOS__)
2393 return wxInvalidSize
;
2394 #elif defined(__WIN32__)
2395 wxFileHandle
f(filename
, wxFileHandle::Read
);
2397 return wxInvalidSize
;
2399 DWORD lpFileSizeHigh
;
2400 DWORD ret
= GetFileSize(f
, &lpFileSizeHigh
);
2401 if ( ret
== INVALID_FILE_SIZE
&& ::GetLastError() != NO_ERROR
)
2402 return wxInvalidSize
;
2404 return wxULongLong(lpFileSizeHigh
, ret
);
2405 #else // ! __WIN32__
2407 #ifndef wxNEED_WX_UNISTD_H
2408 if (wxStat( filename
.fn_str() , &st
) != 0)
2410 if (wxStat( filename
, &st
) != 0)
2412 return wxInvalidSize
;
2413 return wxULongLong(st
.st_size
);
2418 wxString
wxFileName::GetHumanReadableSize(const wxULongLong
&bs
,
2419 const wxString
&nullsize
,
2422 static const double KILOBYTESIZE
= 1024.0;
2423 static const double MEGABYTESIZE
= 1024.0*KILOBYTESIZE
;
2424 static const double GIGABYTESIZE
= 1024.0*MEGABYTESIZE
;
2425 static const double TERABYTESIZE
= 1024.0*GIGABYTESIZE
;
2427 if (bs
== 0 || bs
== wxInvalidSize
)
2430 double bytesize
= bs
.ToDouble();
2431 if (bytesize
< KILOBYTESIZE
)
2432 return wxString::Format(_("%s B"), bs
.ToString().c_str());
2433 if (bytesize
< MEGABYTESIZE
)
2434 return wxString::Format(_("%.*f kB"), precision
, bytesize
/KILOBYTESIZE
);
2435 if (bytesize
< GIGABYTESIZE
)
2436 return wxString::Format(_("%.*f MB"), precision
, bytesize
/MEGABYTESIZE
);
2437 if (bytesize
< TERABYTESIZE
)
2438 return wxString::Format(_("%.*f GB"), precision
, bytesize
/GIGABYTESIZE
);
2440 return wxString::Format(_("%.*f TB"), precision
, bytesize
/TERABYTESIZE
);
2443 wxULongLong
wxFileName::GetSize() const
2445 return GetSize(GetFullPath());
2448 wxString
wxFileName::GetHumanReadableSize(const wxString
&failmsg
, int precision
) const
2450 return GetHumanReadableSize(GetSize(), failmsg
, precision
);
2453 #endif // wxUSE_LONGLONG
2455 // ----------------------------------------------------------------------------
2456 // Mac-specific functions
2457 // ----------------------------------------------------------------------------
2459 #if defined( __WXOSX_MAC__ ) && wxOSX_USE_CARBON
2464 class MacDefaultExtensionRecord
2467 MacDefaultExtensionRecord()
2473 // default copy ctor, assignment operator and dtor are ok
2475 MacDefaultExtensionRecord(const wxString
& ext
, OSType type
, OSType creator
)
2479 m_creator
= creator
;
2487 WX_DECLARE_OBJARRAY(MacDefaultExtensionRecord
, MacDefaultExtensionArray
);
2489 bool gMacDefaultExtensionsInited
= false;
2491 #include "wx/arrimpl.cpp"
2493 WX_DEFINE_EXPORTED_OBJARRAY(MacDefaultExtensionArray
);
2495 MacDefaultExtensionArray gMacDefaultExtensions
;
2497 // load the default extensions
2498 const MacDefaultExtensionRecord gDefaults
[] =
2500 MacDefaultExtensionRecord( "txt", 'TEXT', 'ttxt' ),
2501 MacDefaultExtensionRecord( "tif", 'TIFF', '****' ),
2502 MacDefaultExtensionRecord( "jpg", 'JPEG', '****' ),
2505 void MacEnsureDefaultExtensionsLoaded()
2507 if ( !gMacDefaultExtensionsInited
)
2509 // we could load the pc exchange prefs here too
2510 for ( size_t i
= 0 ; i
< WXSIZEOF( gDefaults
) ; ++i
)
2512 gMacDefaultExtensions
.Add( gDefaults
[i
] ) ;
2514 gMacDefaultExtensionsInited
= true;
2518 } // anonymous namespace
2520 bool wxFileName::MacSetTypeAndCreator( wxUint32 type
, wxUint32 creator
)
2523 FSCatalogInfo catInfo
;
2526 if ( wxMacPathToFSRef( GetFullPath() , &fsRef
) == noErr
)
2528 if ( FSGetCatalogInfo (&fsRef
, kFSCatInfoFinderInfo
, &catInfo
, NULL
, NULL
, NULL
) == noErr
)
2530 finfo
= (FileInfo
*)&catInfo
.finderInfo
;
2531 finfo
->fileType
= type
;
2532 finfo
->fileCreator
= creator
;
2533 FSSetCatalogInfo( &fsRef
, kFSCatInfoFinderInfo
, &catInfo
) ;
2540 bool wxFileName::MacGetTypeAndCreator( wxUint32
*type
, wxUint32
*creator
)
2543 FSCatalogInfo catInfo
;
2546 if ( wxMacPathToFSRef( GetFullPath() , &fsRef
) == noErr
)
2548 if ( FSGetCatalogInfo (&fsRef
, kFSCatInfoFinderInfo
, &catInfo
, NULL
, NULL
, NULL
) == noErr
)
2550 finfo
= (FileInfo
*)&catInfo
.finderInfo
;
2551 *type
= finfo
->fileType
;
2552 *creator
= finfo
->fileCreator
;
2559 bool wxFileName::MacSetDefaultTypeAndCreator()
2561 wxUint32 type
, creator
;
2562 if ( wxFileName::MacFindDefaultTypeAndCreator(GetExt() , &type
,
2565 return MacSetTypeAndCreator( type
, creator
) ;
2570 bool wxFileName::MacFindDefaultTypeAndCreator( const wxString
& ext
, wxUint32
*type
, wxUint32
*creator
)
2572 MacEnsureDefaultExtensionsLoaded() ;
2573 wxString extl
= ext
.Lower() ;
2574 for( int i
= gMacDefaultExtensions
.Count() - 1 ; i
>= 0 ; --i
)
2576 if ( gMacDefaultExtensions
.Item(i
).m_ext
== extl
)
2578 *type
= gMacDefaultExtensions
.Item(i
).m_type
;
2579 *creator
= gMacDefaultExtensions
.Item(i
).m_creator
;
2586 void wxFileName::MacRegisterDefaultTypeAndCreator( const wxString
& ext
, wxUint32 type
, wxUint32 creator
)
2588 MacEnsureDefaultExtensionsLoaded();
2589 MacDefaultExtensionRecord
rec(ext
.Lower(), type
, creator
);
2590 gMacDefaultExtensions
.Add( rec
);
2593 #endif // defined( __WXOSX_MAC__ ) && wxOSX_USE_CARBON