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"
80 #include "wx/filename.h"
81 #include "wx/private/filename.h"
82 #include "wx/tokenzr.h"
83 #include "wx/config.h" // for wxExpandEnvVars
84 #include "wx/dynlib.h"
86 #if defined(__WIN32__) && defined(__MINGW32__)
87 #include "wx/msw/gccpriv.h"
91 #include "wx/msw/private.h"
94 #if defined(__WXMAC__)
95 #include "wx/mac/private.h" // includes mac headers
98 // utime() is POSIX so should normally be available on all Unices
100 #include <sys/types.h>
102 #include <sys/stat.h>
112 #include <sys/types.h>
114 #include <sys/stat.h>
125 #include <sys/utime.h>
126 #include <sys/stat.h>
137 #define MAX_PATH _MAX_PATH
141 wxULongLong wxInvalidSize
= (unsigned)-1;
144 // ----------------------------------------------------------------------------
146 // ----------------------------------------------------------------------------
148 // small helper class which opens and closes the file - we use it just to get
149 // a file handle for the given file name to pass it to some Win32 API function
150 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
161 wxFileHandle(const wxString
& filename
, OpenMode mode
)
163 m_hFile
= ::CreateFile
166 mode
== Read
? GENERIC_READ
// access mask
168 FILE_SHARE_READ
| // sharing mode
169 FILE_SHARE_WRITE
, // (allow everything)
170 NULL
, // no secutity attr
171 OPEN_EXISTING
, // creation disposition
173 NULL
// no template file
176 if ( m_hFile
== INVALID_HANDLE_VALUE
)
178 wxLogSysError(_("Failed to open '%s' for %s"),
180 mode
== Read
? _("reading") : _("writing"));
186 if ( m_hFile
!= INVALID_HANDLE_VALUE
)
188 if ( !::CloseHandle(m_hFile
) )
190 wxLogSysError(_("Failed to close file handle"));
195 // return true only if the file could be opened successfully
196 bool IsOk() const { return m_hFile
!= INVALID_HANDLE_VALUE
; }
199 operator HANDLE() const { return m_hFile
; }
207 // ----------------------------------------------------------------------------
209 // ----------------------------------------------------------------------------
211 #if wxUSE_DATETIME && defined(__WIN32__) && !defined(__WXMICROWIN__)
213 // convert between wxDateTime and FILETIME which is a 64-bit value representing
214 // the number of 100-nanosecond intervals since January 1, 1601.
216 static void ConvertFileTimeToWx(wxDateTime
*dt
, const FILETIME
&ft
)
218 FILETIME ftcopy
= ft
;
220 if ( !::FileTimeToLocalFileTime(&ftcopy
, &ftLocal
) )
222 wxLogLastError(_T("FileTimeToLocalFileTime"));
226 if ( !::FileTimeToSystemTime(&ftLocal
, &st
) )
228 wxLogLastError(_T("FileTimeToSystemTime"));
231 dt
->Set(st
.wDay
, wxDateTime::Month(st
.wMonth
- 1), st
.wYear
,
232 st
.wHour
, st
.wMinute
, st
.wSecond
, st
.wMilliseconds
);
235 static void ConvertWxToFileTime(FILETIME
*ft
, const wxDateTime
& dt
)
238 st
.wDay
= dt
.GetDay();
239 st
.wMonth
= (WORD
)(dt
.GetMonth() + 1);
240 st
.wYear
= (WORD
)dt
.GetYear();
241 st
.wHour
= dt
.GetHour();
242 st
.wMinute
= dt
.GetMinute();
243 st
.wSecond
= dt
.GetSecond();
244 st
.wMilliseconds
= dt
.GetMillisecond();
247 if ( !::SystemTimeToFileTime(&st
, &ftLocal
) )
249 wxLogLastError(_T("SystemTimeToFileTime"));
252 if ( !::LocalFileTimeToFileTime(&ftLocal
, ft
) )
254 wxLogLastError(_T("LocalFileTimeToFileTime"));
258 #endif // wxUSE_DATETIME && __WIN32__
260 // return a string with the volume par
261 static wxString
wxGetVolumeString(const wxString
& volume
, wxPathFormat format
)
265 if ( !volume
.empty() )
267 format
= wxFileName::GetFormat(format
);
269 // Special Windows UNC paths hack, part 2: undo what we did in
270 // SplitPath() and make an UNC path if we have a drive which is not a
271 // single letter (hopefully the network shares can't be one letter only
272 // although I didn't find any authoritative docs on this)
273 if ( format
== wxPATH_DOS
&& volume
.length() > 1 )
275 path
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_DOS
<< volume
;
277 else if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
279 path
<< volume
<< wxFileName::GetVolumeSeparator(format
);
287 // ============================================================================
289 // ============================================================================
291 // ----------------------------------------------------------------------------
292 // wxFileName construction
293 // ----------------------------------------------------------------------------
295 void wxFileName::Assign( const wxFileName
&filepath
)
297 m_volume
= filepath
.GetVolume();
298 m_dirs
= filepath
.GetDirs();
299 m_name
= filepath
.GetName();
300 m_ext
= filepath
.GetExt();
301 m_relative
= filepath
.m_relative
;
302 m_hasExt
= filepath
.m_hasExt
;
305 void wxFileName::Assign(const wxString
& volume
,
306 const wxString
& path
,
307 const wxString
& name
,
310 wxPathFormat format
)
312 SetPath( path
, format
);
321 void wxFileName::SetPath( const wxString
& pathOrig
, wxPathFormat format
)
325 if ( pathOrig
.empty() )
333 format
= GetFormat( format
);
335 // 0) deal with possible volume part first
338 SplitVolume(pathOrig
, &volume
, &path
, format
);
339 if ( !volume
.empty() )
346 // 1) Determine if the path is relative or absolute.
347 wxChar leadingChar
= path
[0u];
352 m_relative
= leadingChar
== wxT(':');
354 // We then remove a leading ":". The reason is in our
355 // storage form for relative paths:
356 // ":dir:file.txt" actually means "./dir/file.txt" in
357 // DOS notation and should get stored as
358 // (relative) (dir) (file.txt)
359 // "::dir:file.txt" actually means "../dir/file.txt"
360 // stored as (relative) (..) (dir) (file.txt)
361 // This is important only for the Mac as an empty dir
362 // actually means <UP>, whereas under DOS, double
363 // slashes can be ignored: "\\\\" is the same as "\\".
369 // TODO: what is the relative path format here?
374 wxFAIL_MSG( _T("Unknown path format") );
375 // !! Fall through !!
378 // the paths of the form "~" or "~username" are absolute
379 m_relative
= leadingChar
!= wxT('/') && leadingChar
!= _T('~');
383 m_relative
= !IsPathSeparator(leadingChar
, format
);
388 // 2) Break up the path into its members. If the original path
389 // was just "/" or "\\", m_dirs will be empty. We know from
390 // the m_relative field, if this means "nothing" or "root dir".
392 wxStringTokenizer
tn( path
, GetPathSeparators(format
) );
394 while ( tn
.HasMoreTokens() )
396 wxString token
= tn
.GetNextToken();
398 // Remove empty token under DOS and Unix, interpret them
402 if (format
== wxPATH_MAC
)
403 m_dirs
.Add( wxT("..") );
413 void wxFileName::Assign(const wxString
& fullpath
,
416 wxString volume
, path
, name
, ext
;
418 SplitPath(fullpath
, &volume
, &path
, &name
, &ext
, &hasExt
, format
);
420 Assign(volume
, path
, name
, ext
, hasExt
, format
);
423 void wxFileName::Assign(const wxString
& fullpathOrig
,
424 const wxString
& fullname
,
427 // always recognize fullpath as directory, even if it doesn't end with a
429 wxString fullpath
= fullpathOrig
;
430 if ( !wxEndsWithPathSeparator(fullpath
) )
432 fullpath
+= GetPathSeparator(format
);
435 wxString volume
, path
, name
, ext
;
438 // do some consistency checks in debug mode: the name should be really just
439 // the filename and the path should be really just a path
441 wxString volDummy
, pathDummy
, nameDummy
, extDummy
;
443 SplitPath(fullname
, &volDummy
, &pathDummy
, &name
, &ext
, &hasExt
, format
);
445 wxASSERT_MSG( volDummy
.empty() && pathDummy
.empty(),
446 _T("the file name shouldn't contain the path") );
448 SplitPath(fullpath
, &volume
, &path
, &nameDummy
, &extDummy
, format
);
450 wxASSERT_MSG( nameDummy
.empty() && extDummy
.empty(),
451 _T("the path shouldn't contain file name nor extension") );
453 #else // !__WXDEBUG__
454 SplitPath(fullname
, NULL
/* no volume */, NULL
/* no path */,
455 &name
, &ext
, &hasExt
, format
);
456 SplitPath(fullpath
, &volume
, &path
, NULL
, NULL
, format
);
457 #endif // __WXDEBUG__/!__WXDEBUG__
459 Assign(volume
, path
, name
, ext
, hasExt
, format
);
462 void wxFileName::Assign(const wxString
& pathOrig
,
463 const wxString
& name
,
469 SplitVolume(pathOrig
, &volume
, &path
, format
);
471 Assign(volume
, path
, name
, ext
, format
);
474 void wxFileName::AssignDir(const wxString
& dir
, wxPathFormat format
)
476 Assign(dir
, wxEmptyString
, format
);
479 void wxFileName::Clear()
485 m_ext
= wxEmptyString
;
487 // we don't have any absolute path for now
495 wxFileName
wxFileName::FileName(const wxString
& file
, wxPathFormat format
)
497 return wxFileName(file
, format
);
501 wxFileName
wxFileName::DirName(const wxString
& dir
, wxPathFormat format
)
504 fn
.AssignDir(dir
, format
);
508 // ----------------------------------------------------------------------------
510 // ----------------------------------------------------------------------------
512 bool wxFileName::FileExists() const
514 return wxFileName::FileExists( GetFullPath() );
517 bool wxFileName::FileExists( const wxString
&file
)
519 return ::wxFileExists( file
);
522 bool wxFileName::DirExists() const
524 return wxFileName::DirExists( GetPath() );
527 bool wxFileName::DirExists( const wxString
&dir
)
529 return ::wxDirExists( dir
);
532 // ----------------------------------------------------------------------------
533 // CWD and HOME stuff
534 // ----------------------------------------------------------------------------
536 void wxFileName::AssignCwd(const wxString
& volume
)
538 AssignDir(wxFileName::GetCwd(volume
));
542 wxString
wxFileName::GetCwd(const wxString
& volume
)
544 // if we have the volume, we must get the current directory on this drive
545 // and to do this we have to chdir to this volume - at least under Windows,
546 // I don't know how to get the current drive on another volume elsewhere
549 if ( !volume
.empty() )
552 SetCwd(volume
+ GetVolumeSeparator());
555 wxString cwd
= ::wxGetCwd();
557 if ( !volume
.empty() )
565 bool wxFileName::SetCwd()
567 return wxFileName::SetCwd( GetPath() );
570 bool wxFileName::SetCwd( const wxString
&cwd
)
572 return ::wxSetWorkingDirectory( cwd
);
575 void wxFileName::AssignHomeDir()
577 AssignDir(wxFileName::GetHomeDir());
580 wxString
wxFileName::GetHomeDir()
582 return ::wxGetHomeDir();
586 // ----------------------------------------------------------------------------
587 // CreateTempFileName
588 // ----------------------------------------------------------------------------
590 #if wxUSE_FILE || wxUSE_FFILE
593 #if !defined wx_fdopen && defined HAVE_FDOPEN
594 #define wx_fdopen fdopen
597 // NB: GetTempFileName() under Windows creates the file, so using
598 // O_EXCL there would fail
600 #define wxOPEN_EXCL 0
602 #define wxOPEN_EXCL O_EXCL
606 #ifdef wxOpenOSFHandle
607 #define WX_HAVE_DELETE_ON_CLOSE
608 // On Windows create a file with the FILE_FLAGS_DELETE_ON_CLOSE flags.
610 static int wxOpenWithDeleteOnClose(const wxString
& filename
)
612 DWORD access
= GENERIC_READ
| GENERIC_WRITE
;
614 DWORD disposition
= OPEN_ALWAYS
;
616 DWORD attributes
= FILE_ATTRIBUTE_TEMPORARY
|
617 FILE_FLAG_DELETE_ON_CLOSE
;
619 HANDLE h
= ::CreateFile(filename
, access
, 0, NULL
,
620 disposition
, attributes
, NULL
);
622 return wxOpenOSFHandle(h
, 0);
624 #endif // wxOpenOSFHandle
627 // Helper to open the file
629 static int wxTempOpen(const wxString
& path
, bool *deleteOnClose
)
631 #ifdef WX_HAVE_DELETE_ON_CLOSE
633 return wxOpenWithDeleteOnClose(path
);
636 *deleteOnClose
= false;
638 return wxOpen(path
, wxO_BINARY
| O_RDWR
| O_CREAT
| wxOPEN_EXCL
, 0600);
643 // Helper to open the file and attach it to the wxFFile
645 static bool wxTempOpen(wxFFile
*file
, const wxString
& path
, bool *deleteOnClose
)
648 *deleteOnClose
= false;
649 return file
->Open(path
, _T("w+b"));
651 int fd
= wxTempOpen(path
, deleteOnClose
);
654 file
->Attach(wx_fdopen(fd
, "w+b"));
655 return file
->IsOpened();
658 #endif // wxUSE_FFILE
662 #define WXFILEARGS(x, y) y
664 #define WXFILEARGS(x, y) x
666 #define WXFILEARGS(x, y) x, y
670 // Implementation of wxFileName::CreateTempFileName().
672 static wxString
wxCreateTempImpl(
673 const wxString
& prefix
,
674 WXFILEARGS(wxFile
*fileTemp
, wxFFile
*ffileTemp
),
675 bool *deleteOnClose
= NULL
)
677 #if wxUSE_FILE && wxUSE_FFILE
678 wxASSERT(fileTemp
== NULL
|| ffileTemp
== NULL
);
680 wxString path
, dir
, name
;
681 bool wantDeleteOnClose
= false;
685 // set the result to false initially
686 wantDeleteOnClose
= *deleteOnClose
;
687 *deleteOnClose
= false;
691 // easier if it alwasys points to something
692 deleteOnClose
= &wantDeleteOnClose
;
695 // use the directory specified by the prefix
696 wxFileName::SplitPath(prefix
, &dir
, &name
, NULL
/* extension */);
700 dir
= wxFileName::GetTempDir();
703 #if defined(__WXWINCE__)
704 path
= dir
+ wxT("\\") + name
;
706 while (wxFileName::FileExists(path
))
708 path
= dir
+ wxT("\\") + name
;
713 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
714 if ( !::GetTempFileName(dir
, name
, 0, wxStringBuffer(path
, MAX_PATH
+ 1)) )
716 wxLogLastError(_T("GetTempFileName"));
724 if ( !wxEndsWithPathSeparator(dir
) &&
725 (name
.empty() || !wxIsPathSeparator(name
[0u])) )
727 path
+= wxFILE_SEP_PATH
;
732 #if defined(HAVE_MKSTEMP)
733 // scratch space for mkstemp()
734 path
+= _T("XXXXXX");
736 // we need to copy the path to the buffer in which mkstemp() can modify it
737 wxCharBuffer
buf( wxConvFile
.cWX2MB( path
) );
739 // cast is safe because the string length doesn't change
740 int fdTemp
= mkstemp( (char*)(const char*) buf
);
743 // this might be not necessary as mkstemp() on most systems should have
744 // already done it but it doesn't hurt neither...
747 else // mkstemp() succeeded
749 path
= wxConvFile
.cMB2WX( (const char*) buf
);
752 // avoid leaking the fd
755 fileTemp
->Attach(fdTemp
);
764 ffileTemp
->Attach(wx_fdopen(fdTemp
, "r+b"));
766 ffileTemp
->Open(path
, _T("r+b"));
777 #else // !HAVE_MKSTEMP
781 path
+= _T("XXXXXX");
783 wxCharBuffer buf
= wxConvFile
.cWX2MB( path
);
784 if ( !mktemp( (char*)(const char*) buf
) )
790 path
= wxConvFile
.cMB2WX( (const char*) buf
);
792 #else // !HAVE_MKTEMP (includes __DOS__)
793 // generate the unique file name ourselves
794 #if !defined(__DOS__) && !defined(__PALMOS__) && (!defined(__MWERKS__) || defined(__DARWIN__) )
795 path
<< (unsigned int)getpid();
800 static const size_t numTries
= 1000;
801 for ( size_t n
= 0; n
< numTries
; n
++ )
803 // 3 hex digits is enough for numTries == 1000 < 4096
804 pathTry
= path
+ wxString::Format(_T("%.03x"), (unsigned int) n
);
805 if ( !wxFileName::FileExists(pathTry
) )
814 #endif // HAVE_MKTEMP/!HAVE_MKTEMP
816 #endif // HAVE_MKSTEMP/!HAVE_MKSTEMP
818 #endif // Windows/!Windows
822 wxLogSysError(_("Failed to create a temporary file name"));
828 // open the file - of course, there is a race condition here, this is
829 // why we always prefer using mkstemp()...
831 if ( fileTemp
&& !fileTemp
->IsOpened() )
833 *deleteOnClose
= wantDeleteOnClose
;
834 int fd
= wxTempOpen(path
, deleteOnClose
);
836 fileTemp
->Attach(fd
);
843 if ( ffileTemp
&& !ffileTemp
->IsOpened() )
845 *deleteOnClose
= wantDeleteOnClose
;
846 ok
= wxTempOpen(ffileTemp
, path
, deleteOnClose
);
852 // FIXME: If !ok here should we loop and try again with another
853 // file name? That is the standard recourse if open(O_EXCL)
854 // fails, though of course it should be protected against
855 // possible infinite looping too.
857 wxLogError(_("Failed to open temporary file."));
867 static bool wxCreateTempImpl(
868 const wxString
& prefix
,
869 WXFILEARGS(wxFile
*fileTemp
, wxFFile
*ffileTemp
),
872 bool deleteOnClose
= true;
874 *name
= wxCreateTempImpl(prefix
,
875 WXFILEARGS(fileTemp
, ffileTemp
),
878 bool ok
= !name
->empty();
883 else if (ok
&& wxRemoveFile(*name
))
891 static void wxAssignTempImpl(
893 const wxString
& prefix
,
894 WXFILEARGS(wxFile
*fileTemp
, wxFFile
*ffileTemp
))
897 tempname
= wxCreateTempImpl(prefix
, WXFILEARGS(fileTemp
, ffileTemp
));
899 if ( tempname
.empty() )
901 // error, failed to get temp file name
906 fn
->Assign(tempname
);
911 void wxFileName::AssignTempFileName(const wxString
& prefix
)
913 wxAssignTempImpl(this, prefix
, WXFILEARGS(NULL
, NULL
));
917 wxString
wxFileName::CreateTempFileName(const wxString
& prefix
)
919 return wxCreateTempImpl(prefix
, WXFILEARGS(NULL
, NULL
));
922 #endif // wxUSE_FILE || wxUSE_FFILE
927 wxString
wxCreateTempFileName(const wxString
& prefix
,
931 return wxCreateTempImpl(prefix
, WXFILEARGS(fileTemp
, NULL
), deleteOnClose
);
934 bool wxCreateTempFile(const wxString
& prefix
,
938 return wxCreateTempImpl(prefix
, WXFILEARGS(fileTemp
, NULL
), name
);
941 void wxFileName::AssignTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
943 wxAssignTempImpl(this, prefix
, WXFILEARGS(fileTemp
, NULL
));
948 wxFileName::CreateTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
950 return wxCreateTempFileName(prefix
, fileTemp
);
958 wxString
wxCreateTempFileName(const wxString
& prefix
,
962 return wxCreateTempImpl(prefix
, WXFILEARGS(NULL
, fileTemp
), deleteOnClose
);
965 bool wxCreateTempFile(const wxString
& prefix
,
969 return wxCreateTempImpl(prefix
, WXFILEARGS(NULL
, fileTemp
), name
);
973 void wxFileName::AssignTempFileName(const wxString
& prefix
, wxFFile
*fileTemp
)
975 wxAssignTempImpl(this, prefix
, WXFILEARGS(NULL
, fileTemp
));
980 wxFileName::CreateTempFileName(const wxString
& prefix
, wxFFile
*fileTemp
)
982 return wxCreateTempFileName(prefix
, fileTemp
);
985 #endif // wxUSE_FFILE
988 // ----------------------------------------------------------------------------
989 // directory operations
990 // ----------------------------------------------------------------------------
992 wxString
wxFileName::GetTempDir()
995 dir
= wxGetenv(_T("TMPDIR"));
998 dir
= wxGetenv(_T("TMP"));
1001 dir
= wxGetenv(_T("TEMP"));
1005 #if defined(__WXWINCE__)
1008 // FIXME. Create \temp dir?
1009 if (DirExists(wxT("\\temp")))
1010 dir
= wxT("\\temp");
1012 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1016 if ( !::GetTempPath(MAX_PATH
, wxStringBuffer(dir
, MAX_PATH
+ 1)) )
1018 wxLogLastError(_T("GetTempPath"));
1023 // GetTempFileName() fails if we pass it an empty string
1032 #if defined(__DOS__) || defined(__OS2__)
1034 #elif defined(__WXMAC__)
1035 dir
= wxMacFindFolder(short(kOnSystemDisk
), kTemporaryFolderType
, kCreateFolder
);
1045 bool wxFileName::Mkdir( int perm
, int flags
)
1047 return wxFileName::Mkdir(GetPath(), perm
, flags
);
1050 bool wxFileName::Mkdir( const wxString
& dir
, int perm
, int flags
)
1052 if ( flags
& wxPATH_MKDIR_FULL
)
1054 // split the path in components
1055 wxFileName filename
;
1056 filename
.AssignDir(dir
);
1059 if ( filename
.HasVolume())
1061 currPath
<< wxGetVolumeString(filename
.GetVolume(), wxPATH_NATIVE
);
1064 wxArrayString dirs
= filename
.GetDirs();
1065 size_t count
= dirs
.GetCount();
1066 for ( size_t i
= 0; i
< count
; i
++ )
1069 #if defined(__WXMAC__) && !defined(__DARWIN__)
1070 // relative pathnames are exactely the other way round under mac...
1071 !filename
.IsAbsolute()
1073 filename
.IsAbsolute()
1076 currPath
+= wxFILE_SEP_PATH
;
1077 currPath
+= dirs
[i
];
1079 if (!DirExists(currPath
))
1081 if (!wxMkdir(currPath
, perm
))
1083 // no need to try creating further directories
1093 return ::wxMkdir( dir
, perm
);
1096 bool wxFileName::Rmdir()
1098 return wxFileName::Rmdir( GetPath() );
1101 bool wxFileName::Rmdir( const wxString
&dir
)
1103 return ::wxRmdir( dir
);
1106 // ----------------------------------------------------------------------------
1107 // path normalization
1108 // ----------------------------------------------------------------------------
1110 bool wxFileName::Normalize(int flags
,
1111 const wxString
& cwd
,
1112 wxPathFormat format
)
1114 // deal with env vars renaming first as this may seriously change the path
1115 if ( flags
& wxPATH_NORM_ENV_VARS
)
1117 wxString pathOrig
= GetFullPath(format
);
1118 wxString path
= wxExpandEnvVars(pathOrig
);
1119 if ( path
!= pathOrig
)
1126 // the existing path components
1127 wxArrayString dirs
= GetDirs();
1129 // the path to prepend in front to make the path absolute
1132 format
= GetFormat(format
);
1134 // set up the directory to use for making the path absolute later
1135 if ( (flags
& wxPATH_NORM_ABSOLUTE
) && !IsAbsolute(format
) )
1139 curDir
.AssignCwd(GetVolume());
1141 else // cwd provided
1143 curDir
.AssignDir(cwd
);
1147 // handle ~ stuff under Unix only
1148 if ( (format
== wxPATH_UNIX
) && (flags
& wxPATH_NORM_TILDE
) )
1150 if ( !dirs
.IsEmpty() )
1152 wxString dir
= dirs
[0u];
1153 if ( !dir
.empty() && dir
[0u] == _T('~') )
1155 // to make the path absolute use the home directory
1156 curDir
.AssignDir(wxGetUserHome(dir
.c_str() + 1));
1158 // if we are expanding the tilde, then this path
1159 // *should* be already relative (since we checked for
1160 // the tilde only in the first char of the first dir);
1161 // if m_relative==false, it's because it was initialized
1162 // from a string which started with /~; in that case
1163 // we reach this point but then need m_relative=true
1164 // for relative->absolute expansion later
1172 // transform relative path into abs one
1173 if ( curDir
.IsOk() )
1175 // this path may be relative because it doesn't have the volume name
1176 // and still have m_relative=true; in this case we shouldn't modify
1177 // our directory components but just set the current volume
1178 if ( !HasVolume() && curDir
.HasVolume() )
1180 SetVolume(curDir
.GetVolume());
1184 // yes, it was the case - we don't need curDir then
1189 // finally, prepend curDir to the dirs array
1190 wxArrayString dirsNew
= curDir
.GetDirs();
1191 WX_PREPEND_ARRAY(dirs
, dirsNew
);
1193 // if we used e.g. tilde expansion previously and wxGetUserHome didn't
1194 // return for some reason an absolute path, then curDir maybe not be absolute!
1195 if ( curDir
.IsAbsolute(format
) )
1197 // we have prepended an absolute path and thus we are now an absolute
1201 // else if (flags & wxPATH_NORM_ABSOLUTE):
1202 // should we warn the user that we didn't manage to make the path absolute?
1205 // now deal with ".", ".." and the rest
1207 size_t count
= dirs
.GetCount();
1208 for ( size_t n
= 0; n
< count
; n
++ )
1210 wxString dir
= dirs
[n
];
1212 if ( flags
& wxPATH_NORM_DOTS
)
1214 if ( dir
== wxT(".") )
1220 if ( dir
== wxT("..") )
1222 if ( m_dirs
.IsEmpty() )
1224 wxLogError(_("The path '%s' contains too many \"..\"!"),
1225 GetFullPath().c_str());
1229 m_dirs
.RemoveAt(m_dirs
.GetCount() - 1);
1234 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
1242 #if defined(__WIN32__) && !defined(__WXWINCE__) && wxUSE_OLE
1243 if ( (flags
& wxPATH_NORM_SHORTCUT
) )
1246 if (GetShortcutTarget(GetFullPath(format
), filename
))
1248 // Repeat this since we may now have a new path
1249 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
1251 filename
.MakeLower();
1259 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
1261 // VZ: expand env vars here too?
1263 m_volume
.MakeLower();
1268 #if defined(__WIN32__)
1269 if ( (flags
& wxPATH_NORM_LONG
) && (format
== wxPATH_DOS
) )
1271 Assign(GetLongPath());
1278 // ----------------------------------------------------------------------------
1279 // get the shortcut target
1280 // ----------------------------------------------------------------------------
1282 // WinCE (3) doesn't have CLSID_ShellLink, IID_IShellLink definitions.
1283 // The .lnk file is a plain text file so it should be easy to
1284 // make it work. Hint from Google Groups:
1285 // "If you open up a lnk file, you'll see a
1286 // number, followed by a pound sign (#), followed by more text. The
1287 // number is the number of characters that follows the pound sign. The
1288 // characters after the pound sign are the command line (which _can_
1289 // include arguments) to be executed. Any path (e.g. \windows\program
1290 // files\myapp.exe) that includes spaces needs to be enclosed in
1291 // quotation marks."
1293 #if defined(__WIN32__) && !defined(__WXWINCE__) && wxUSE_OLE
1294 // The following lines are necessary under WinCE
1295 // #include "wx/msw/private.h"
1296 // #include <ole2.h>
1298 #if defined(__WXWINCE__)
1299 #include <shlguid.h>
1302 bool wxFileName::GetShortcutTarget(const wxString
& shortcutPath
,
1303 wxString
& targetFilename
,
1304 wxString
* arguments
)
1306 wxString path
, file
, ext
;
1307 wxSplitPath(shortcutPath
, & path
, & file
, & ext
);
1311 bool success
= false;
1313 // Assume it's not a shortcut if it doesn't end with lnk
1314 if (ext
.CmpNoCase(wxT("lnk"))!=0)
1317 // create a ShellLink object
1318 hres
= CoCreateInstance(CLSID_ShellLink
, NULL
, CLSCTX_INPROC_SERVER
,
1319 IID_IShellLink
, (LPVOID
*) &psl
);
1321 if (SUCCEEDED(hres
))
1324 hres
= psl
->QueryInterface( IID_IPersistFile
, (LPVOID
*) &ppf
);
1325 if (SUCCEEDED(hres
))
1327 WCHAR wsz
[MAX_PATH
];
1329 MultiByteToWideChar(CP_ACP
, MB_PRECOMPOSED
, shortcutPath
.mb_str(), -1, wsz
,
1332 hres
= ppf
->Load(wsz
, 0);
1335 if (SUCCEEDED(hres
))
1338 // Wrong prototype in early versions
1339 #if defined(__MINGW32__) && !wxCHECK_W32API_VERSION(2, 2)
1340 psl
->GetPath((CHAR
*) buf
, 2048, NULL
, SLGP_UNCPRIORITY
);
1342 psl
->GetPath(buf
, 2048, NULL
, SLGP_UNCPRIORITY
);
1344 targetFilename
= wxString(buf
);
1345 success
= (shortcutPath
!= targetFilename
);
1347 psl
->GetArguments(buf
, 2048);
1349 if (!args
.empty() && arguments
)
1361 #endif // __WIN32__ && !__WXWINCE__
1364 // ----------------------------------------------------------------------------
1365 // absolute/relative paths
1366 // ----------------------------------------------------------------------------
1368 bool wxFileName::IsAbsolute(wxPathFormat format
) const
1370 // if our path doesn't start with a path separator, it's not an absolute
1375 if ( !GetVolumeSeparator(format
).empty() )
1377 // this format has volumes and an absolute path must have one, it's not
1378 // enough to have the full path to bean absolute file under Windows
1379 if ( GetVolume().empty() )
1386 bool wxFileName::MakeRelativeTo(const wxString
& pathBase
, wxPathFormat format
)
1388 wxFileName fnBase
= wxFileName::DirName(pathBase
, format
);
1390 // get cwd only once - small time saving
1391 wxString cwd
= wxGetCwd();
1392 Normalize(wxPATH_NORM_ALL
& ~wxPATH_NORM_CASE
, cwd
, format
);
1393 fnBase
.Normalize(wxPATH_NORM_ALL
& ~wxPATH_NORM_CASE
, cwd
, format
);
1395 bool withCase
= IsCaseSensitive(format
);
1397 // we can't do anything if the files live on different volumes
1398 if ( !GetVolume().IsSameAs(fnBase
.GetVolume(), withCase
) )
1404 // same drive, so we don't need our volume
1407 // remove common directories starting at the top
1408 while ( !m_dirs
.IsEmpty() && !fnBase
.m_dirs
.IsEmpty() &&
1409 m_dirs
[0u].IsSameAs(fnBase
.m_dirs
[0u], withCase
) )
1412 fnBase
.m_dirs
.RemoveAt(0);
1415 // add as many ".." as needed
1416 size_t count
= fnBase
.m_dirs
.GetCount();
1417 for ( size_t i
= 0; i
< count
; i
++ )
1419 m_dirs
.Insert(wxT(".."), 0u);
1422 if ( format
== wxPATH_UNIX
|| format
== wxPATH_DOS
)
1424 // a directory made relative with respect to itself is '.' under Unix
1425 // and DOS, by definition (but we don't have to insert "./" for the
1427 if ( m_dirs
.IsEmpty() && IsDir() )
1429 m_dirs
.Add(_T('.'));
1439 // ----------------------------------------------------------------------------
1440 // filename kind tests
1441 // ----------------------------------------------------------------------------
1443 bool wxFileName::SameAs(const wxFileName
& filepath
, wxPathFormat format
) const
1445 wxFileName fn1
= *this,
1448 // get cwd only once - small time saving
1449 wxString cwd
= wxGetCwd();
1450 fn1
.Normalize(wxPATH_NORM_ALL
| wxPATH_NORM_CASE
, cwd
, format
);
1451 fn2
.Normalize(wxPATH_NORM_ALL
| wxPATH_NORM_CASE
, cwd
, format
);
1453 if ( fn1
.GetFullPath() == fn2
.GetFullPath() )
1456 // TODO: compare inodes for Unix, this works even when filenames are
1457 // different but files are the same (symlinks) (VZ)
1463 bool wxFileName::IsCaseSensitive( wxPathFormat format
)
1465 // only Unix filenames are truely case-sensitive
1466 return GetFormat(format
) == wxPATH_UNIX
;
1470 wxString
wxFileName::GetForbiddenChars(wxPathFormat format
)
1472 // Inits to forbidden characters that are common to (almost) all platforms.
1473 wxString strForbiddenChars
= wxT("*?");
1475 // If asserts, wxPathFormat has been changed. In case of a new path format
1476 // addition, the following code might have to be updated.
1477 wxCOMPILE_TIME_ASSERT(wxPATH_MAX
== 5, wxPathFormatChanged
);
1478 switch ( GetFormat(format
) )
1481 wxFAIL_MSG( wxT("Unknown path format") );
1482 // !! Fall through !!
1488 // On a Mac even names with * and ? are allowed (Tested with OS
1489 // 9.2.1 and OS X 10.2.5)
1490 strForbiddenChars
= wxEmptyString
;
1494 strForbiddenChars
+= wxT("\\/:\"<>|");
1501 return strForbiddenChars
;
1505 wxString
wxFileName::GetVolumeSeparator(wxPathFormat
WXUNUSED_IN_WINCE(format
))
1508 return wxEmptyString
;
1512 if ( (GetFormat(format
) == wxPATH_DOS
) ||
1513 (GetFormat(format
) == wxPATH_VMS
) )
1515 sepVol
= wxFILE_SEP_DSK
;
1524 wxString
wxFileName::GetPathSeparators(wxPathFormat format
)
1527 switch ( GetFormat(format
) )
1530 // accept both as native APIs do but put the native one first as
1531 // this is the one we use in GetFullPath()
1532 seps
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_UNIX
;
1536 wxFAIL_MSG( _T("Unknown wxPATH_XXX style") );
1540 seps
= wxFILE_SEP_PATH_UNIX
;
1544 seps
= wxFILE_SEP_PATH_MAC
;
1548 seps
= wxFILE_SEP_PATH_VMS
;
1556 wxString
wxFileName::GetPathTerminators(wxPathFormat format
)
1558 format
= GetFormat(format
);
1560 // under VMS the end of the path is ']', not the path separator used to
1561 // separate the components
1562 return format
== wxPATH_VMS
? wxString(_T(']')) : GetPathSeparators(format
);
1566 bool wxFileName::IsPathSeparator(wxChar ch
, wxPathFormat format
)
1568 // wxString::Find() doesn't work as expected with NUL - it will always find
1569 // it, so test for it separately
1570 return ch
!= _T('\0') && GetPathSeparators(format
).Find(ch
) != wxNOT_FOUND
;
1573 // ----------------------------------------------------------------------------
1574 // path components manipulation
1575 // ----------------------------------------------------------------------------
1577 /* static */ bool wxFileName::IsValidDirComponent(const wxString
& dir
)
1581 wxFAIL_MSG( _T("empty directory passed to wxFileName::InsertDir()") );
1586 const size_t len
= dir
.length();
1587 for ( size_t n
= 0; n
< len
; n
++ )
1589 if ( dir
[n
] == GetVolumeSeparator() || IsPathSeparator(dir
[n
]) )
1591 wxFAIL_MSG( _T("invalid directory component in wxFileName") );
1600 void wxFileName::AppendDir( const wxString
& dir
)
1602 if ( IsValidDirComponent(dir
) )
1606 void wxFileName::PrependDir( const wxString
& dir
)
1611 void wxFileName::InsertDir(size_t before
, const wxString
& dir
)
1613 if ( IsValidDirComponent(dir
) )
1614 m_dirs
.Insert(dir
, before
);
1617 void wxFileName::RemoveDir(size_t pos
)
1619 m_dirs
.RemoveAt(pos
);
1622 // ----------------------------------------------------------------------------
1624 // ----------------------------------------------------------------------------
1626 void wxFileName::SetFullName(const wxString
& fullname
)
1628 SplitPath(fullname
, NULL
/* no volume */, NULL
/* no path */,
1629 &m_name
, &m_ext
, &m_hasExt
);
1632 wxString
wxFileName::GetFullName() const
1634 wxString fullname
= m_name
;
1637 fullname
<< wxFILE_SEP_EXT
<< m_ext
;
1643 wxString
wxFileName::GetPath( int flags
, wxPathFormat format
) const
1645 format
= GetFormat( format
);
1649 // return the volume with the path as well if requested
1650 if ( flags
& wxPATH_GET_VOLUME
)
1652 fullpath
+= wxGetVolumeString(GetVolume(), format
);
1655 // the leading character
1660 fullpath
+= wxFILE_SEP_PATH_MAC
;
1665 fullpath
+= wxFILE_SEP_PATH_DOS
;
1669 wxFAIL_MSG( wxT("Unknown path format") );
1675 // normally the absolute file names start with a slash
1676 // with one exception: the ones like "~/foo.bar" don't
1678 if ( m_dirs
.IsEmpty() || m_dirs
[0u] != _T('~') )
1680 fullpath
+= wxFILE_SEP_PATH_UNIX
;
1686 // no leading character here but use this place to unset
1687 // wxPATH_GET_SEPARATOR flag: under VMS it doesn't make sense
1688 // as, if I understand correctly, there should never be a dot
1689 // before the closing bracket
1690 flags
&= ~wxPATH_GET_SEPARATOR
;
1693 if ( m_dirs
.empty() )
1695 // there is nothing more
1699 // then concatenate all the path components using the path separator
1700 if ( format
== wxPATH_VMS
)
1702 fullpath
+= wxT('[');
1705 const size_t dirCount
= m_dirs
.GetCount();
1706 for ( size_t i
= 0; i
< dirCount
; i
++ )
1711 if ( m_dirs
[i
] == wxT(".") )
1713 // skip appending ':', this shouldn't be done in this
1714 // case as "::" is interpreted as ".." under Unix
1718 // convert back from ".." to nothing
1719 if ( !m_dirs
[i
].IsSameAs(wxT("..")) )
1720 fullpath
+= m_dirs
[i
];
1724 wxFAIL_MSG( wxT("Unexpected path format") );
1725 // still fall through
1729 fullpath
+= m_dirs
[i
];
1733 // TODO: What to do with ".." under VMS
1735 // convert back from ".." to nothing
1736 if ( !m_dirs
[i
].IsSameAs(wxT("..")) )
1737 fullpath
+= m_dirs
[i
];
1741 if ( (flags
& wxPATH_GET_SEPARATOR
) || (i
!= dirCount
- 1) )
1742 fullpath
+= GetPathSeparator(format
);
1745 if ( format
== wxPATH_VMS
)
1747 fullpath
+= wxT(']');
1753 wxString
wxFileName::GetFullPath( wxPathFormat format
) const
1755 // we already have a function to get the path
1756 wxString fullpath
= GetPath(wxPATH_GET_VOLUME
| wxPATH_GET_SEPARATOR
,
1759 // now just add the file name and extension to it
1760 fullpath
+= GetFullName();
1765 // Return the short form of the path (returns identity on non-Windows platforms)
1766 wxString
wxFileName::GetShortPath() const
1768 wxString
path(GetFullPath());
1770 #if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
1771 DWORD sz
= ::GetShortPathName(path
, NULL
, 0);
1775 if ( ::GetShortPathName
1778 wxStringBuffer(pathOut
, sz
),
1790 // Return the long form of the path (returns identity on non-Windows platforms)
1791 wxString
wxFileName::GetLongPath() const
1794 path
= GetFullPath();
1796 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1798 #if wxUSE_DYNAMIC_LOADER
1799 typedef DWORD (WINAPI
*GET_LONG_PATH_NAME
)(const wxChar
*, wxChar
*, DWORD
);
1801 // this is MT-safe as in the worst case we're going to resolve the function
1802 // twice -- but as the result is the same in both threads, it's ok
1803 static GET_LONG_PATH_NAME s_pfnGetLongPathName
= NULL
;
1804 if ( !s_pfnGetLongPathName
)
1806 static bool s_triedToLoad
= false;
1808 if ( !s_triedToLoad
)
1810 s_triedToLoad
= true;
1812 wxDynamicLibrary
dllKernel(_T("kernel32"));
1814 const wxChar
* GetLongPathName
= _T("GetLongPathName")
1819 #endif // Unicode/ANSI
1821 if ( dllKernel
.HasSymbol(GetLongPathName
) )
1823 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
)
1824 dllKernel
.GetSymbol(GetLongPathName
);
1827 // note that kernel32.dll can be unloaded, it stays in memory
1828 // anyhow as all Win32 programs link to it and so it's safe to call
1829 // GetLongPathName() even after unloading it
1833 if ( s_pfnGetLongPathName
)
1835 DWORD dwSize
= (*s_pfnGetLongPathName
)(path
, NULL
, 0);
1838 if ( (*s_pfnGetLongPathName
)
1841 wxStringBuffer(pathOut
, dwSize
),
1849 #endif // wxUSE_DYNAMIC_LOADER
1851 // The OS didn't support GetLongPathName, or some other error.
1852 // We need to call FindFirstFile on each component in turn.
1854 WIN32_FIND_DATA findFileData
;
1858 pathOut
= GetVolume() +
1859 GetVolumeSeparator(wxPATH_DOS
) +
1860 GetPathSeparator(wxPATH_DOS
);
1862 pathOut
= wxEmptyString
;
1864 wxArrayString dirs
= GetDirs();
1865 dirs
.Add(GetFullName());
1869 size_t count
= dirs
.GetCount();
1870 for ( size_t i
= 0; i
< count
; i
++ )
1872 // We're using pathOut to collect the long-name path, but using a
1873 // temporary for appending the last path component which may be
1875 tmpPath
= pathOut
+ dirs
[i
];
1877 if ( tmpPath
.empty() )
1880 // can't see this being necessary? MF
1881 if ( tmpPath
.Last() == GetVolumeSeparator(wxPATH_DOS
) )
1883 // Can't pass a drive and root dir to FindFirstFile,
1884 // so continue to next dir
1885 tmpPath
+= wxFILE_SEP_PATH
;
1890 hFind
= ::FindFirstFile(tmpPath
, &findFileData
);
1891 if (hFind
== INVALID_HANDLE_VALUE
)
1893 // Error: most likely reason is that path doesn't exist, so
1894 // append any unprocessed parts and return
1895 for ( i
+= 1; i
< count
; i
++ )
1896 tmpPath
+= wxFILE_SEP_PATH
+ dirs
[i
];
1901 pathOut
+= findFileData
.cFileName
;
1902 if ( (i
< (count
-1)) )
1903 pathOut
+= wxFILE_SEP_PATH
;
1909 #endif // Win32/!Win32
1914 wxPathFormat
wxFileName::GetFormat( wxPathFormat format
)
1916 if (format
== wxPATH_NATIVE
)
1918 #if defined(__WXMSW__) || defined(__OS2__) || defined(__DOS__)
1919 format
= wxPATH_DOS
;
1920 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1921 format
= wxPATH_MAC
;
1922 #elif defined(__VMS)
1923 format
= wxPATH_VMS
;
1925 format
= wxPATH_UNIX
;
1931 // ----------------------------------------------------------------------------
1932 // path splitting function
1933 // ----------------------------------------------------------------------------
1937 wxFileName::SplitVolume(const wxString
& fullpathWithVolume
,
1938 wxString
*pstrVolume
,
1940 wxPathFormat format
)
1942 format
= GetFormat(format
);
1944 wxString fullpath
= fullpathWithVolume
;
1946 // special Windows UNC paths hack: transform \\share\path into share:path
1947 if ( format
== wxPATH_DOS
)
1949 if ( fullpath
.length() >= 4 &&
1950 fullpath
[0u] == wxFILE_SEP_PATH_DOS
&&
1951 fullpath
[1u] == wxFILE_SEP_PATH_DOS
)
1953 fullpath
.erase(0, 2);
1955 size_t posFirstSlash
=
1956 fullpath
.find_first_of(GetPathTerminators(format
));
1957 if ( posFirstSlash
!= wxString::npos
)
1959 fullpath
[posFirstSlash
] = wxFILE_SEP_DSK
;
1961 // UNC paths are always absolute, right? (FIXME)
1962 fullpath
.insert(posFirstSlash
+ 1, 1, wxFILE_SEP_PATH_DOS
);
1967 // We separate the volume here
1968 if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
1970 wxString sepVol
= GetVolumeSeparator(format
);
1972 size_t posFirstColon
= fullpath
.find_first_of(sepVol
);
1973 if ( posFirstColon
!= wxString::npos
)
1977 *pstrVolume
= fullpath
.Left(posFirstColon
);
1980 // remove the volume name and the separator from the full path
1981 fullpath
.erase(0, posFirstColon
+ sepVol
.length());
1986 *pstrPath
= fullpath
;
1990 void wxFileName::SplitPath(const wxString
& fullpathWithVolume
,
1991 wxString
*pstrVolume
,
1996 wxPathFormat format
)
1998 format
= GetFormat(format
);
2001 SplitVolume(fullpathWithVolume
, pstrVolume
, &fullpath
, format
);
2003 // find the positions of the last dot and last path separator in the path
2004 size_t posLastDot
= fullpath
.find_last_of(wxFILE_SEP_EXT
);
2005 size_t posLastSlash
= fullpath
.find_last_of(GetPathTerminators(format
));
2007 // check whether this dot occurs at the very beginning of a path component
2008 if ( (posLastDot
!= wxString::npos
) &&
2010 IsPathSeparator(fullpath
[posLastDot
- 1]) ||
2011 (format
== wxPATH_VMS
&& fullpath
[posLastDot
- 1] == _T(']'))) )
2013 // dot may be (and commonly -- at least under Unix -- is) the first
2014 // character of the filename, don't treat the entire filename as
2015 // extension in this case
2016 posLastDot
= wxString::npos
;
2019 // if we do have a dot and a slash, check that the dot is in the name part
2020 if ( (posLastDot
!= wxString::npos
) &&
2021 (posLastSlash
!= wxString::npos
) &&
2022 (posLastDot
< posLastSlash
) )
2024 // the dot is part of the path, not the start of the extension
2025 posLastDot
= wxString::npos
;
2028 // now fill in the variables provided by user
2031 if ( posLastSlash
== wxString::npos
)
2038 // take everything up to the path separator but take care to make
2039 // the path equal to something like '/', not empty, for the files
2040 // immediately under root directory
2041 size_t len
= posLastSlash
;
2043 // this rule does not apply to mac since we do not start with colons (sep)
2044 // except for relative paths
2045 if ( !len
&& format
!= wxPATH_MAC
)
2048 *pstrPath
= fullpath
.Left(len
);
2050 // special VMS hack: remove the initial bracket
2051 if ( format
== wxPATH_VMS
)
2053 if ( (*pstrPath
)[0u] == _T('[') )
2054 pstrPath
->erase(0, 1);
2061 // take all characters starting from the one after the last slash and
2062 // up to, but excluding, the last dot
2063 size_t nStart
= posLastSlash
== wxString::npos
? 0 : posLastSlash
+ 1;
2065 if ( posLastDot
== wxString::npos
)
2067 // take all until the end
2068 count
= wxString::npos
;
2070 else if ( posLastSlash
== wxString::npos
)
2074 else // have both dot and slash
2076 count
= posLastDot
- posLastSlash
- 1;
2079 *pstrName
= fullpath
.Mid(nStart
, count
);
2082 // finally deal with the extension here: we have an added complication that
2083 // extension may be empty (but present) as in "foo." where trailing dot
2084 // indicates the empty extension at the end -- and hence we must remember
2085 // that we have it independently of pstrExt
2086 if ( posLastDot
== wxString::npos
)
2096 // take everything after the dot
2098 *pstrExt
= fullpath
.Mid(posLastDot
+ 1);
2105 void wxFileName::SplitPath(const wxString
& fullpath
,
2109 wxPathFormat format
)
2112 SplitPath(fullpath
, &volume
, path
, name
, ext
, format
);
2116 path
->Prepend(wxGetVolumeString(volume
, format
));
2120 // ----------------------------------------------------------------------------
2122 // ----------------------------------------------------------------------------
2126 bool wxFileName::SetTimes(const wxDateTime
*dtAccess
,
2127 const wxDateTime
*dtMod
,
2128 const wxDateTime
*dtCreate
)
2130 #if defined(__WIN32__)
2133 // VZ: please let me know how to do this if you can
2134 wxFAIL_MSG( _T("SetTimes() not implemented for the directories") );
2138 wxFileHandle
fh(GetFullPath(), wxFileHandle::Write
);
2141 FILETIME ftAccess
, ftCreate
, ftWrite
;
2144 ConvertWxToFileTime(&ftCreate
, *dtCreate
);
2146 ConvertWxToFileTime(&ftAccess
, *dtAccess
);
2148 ConvertWxToFileTime(&ftWrite
, *dtMod
);
2150 if ( ::SetFileTime(fh
,
2151 dtCreate
? &ftCreate
: NULL
,
2152 dtAccess
? &ftAccess
: NULL
,
2153 dtMod
? &ftWrite
: NULL
) )
2159 #elif defined(__UNIX_LIKE__) || (defined(__DOS__) && defined(__WATCOMC__))
2160 wxUnusedVar(dtCreate
);
2162 if ( !dtAccess
&& !dtMod
)
2164 // can't modify the creation time anyhow, don't try
2168 // if dtAccess or dtMod is not specified, use the other one (which must be
2169 // non NULL because of the test above) for both times
2171 utm
.actime
= dtAccess
? dtAccess
->GetTicks() : dtMod
->GetTicks();
2172 utm
.modtime
= dtMod
? dtMod
->GetTicks() : dtAccess
->GetTicks();
2173 if ( utime(GetFullPath().fn_str(), &utm
) == 0 )
2177 #else // other platform
2178 wxUnusedVar(dtAccess
);
2180 wxUnusedVar(dtCreate
);
2183 wxLogSysError(_("Failed to modify file times for '%s'"),
2184 GetFullPath().c_str());
2189 bool wxFileName::Touch()
2191 #if defined(__UNIX_LIKE__)
2192 // under Unix touching file is simple: just pass NULL to utime()
2193 if ( utime(GetFullPath().fn_str(), NULL
) == 0 )
2198 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
2201 #else // other platform
2202 wxDateTime dtNow
= wxDateTime::Now();
2204 return SetTimes(&dtNow
, &dtNow
, NULL
/* don't change create time */);
2208 bool wxFileName::GetTimes(wxDateTime
*dtAccess
,
2210 wxDateTime
*dtCreate
) const
2212 #if defined(__WIN32__)
2213 // we must use different methods for the files and directories under
2214 // Windows as CreateFile(GENERIC_READ) doesn't work for the directories and
2215 // CreateFile(FILE_FLAG_BACKUP_SEMANTICS) works -- but only under NT and
2218 FILETIME ftAccess
, ftCreate
, ftWrite
;
2221 // implemented in msw/dir.cpp
2222 extern bool wxGetDirectoryTimes(const wxString
& dirname
,
2223 FILETIME
*, FILETIME
*, FILETIME
*);
2225 // we should pass the path without the trailing separator to
2226 // wxGetDirectoryTimes()
2227 ok
= wxGetDirectoryTimes(GetPath(wxPATH_GET_VOLUME
),
2228 &ftAccess
, &ftCreate
, &ftWrite
);
2232 wxFileHandle
fh(GetFullPath(), wxFileHandle::Read
);
2235 ok
= ::GetFileTime(fh
,
2236 dtCreate
? &ftCreate
: NULL
,
2237 dtAccess
? &ftAccess
: NULL
,
2238 dtMod
? &ftWrite
: NULL
) != 0;
2249 ConvertFileTimeToWx(dtCreate
, ftCreate
);
2251 ConvertFileTimeToWx(dtAccess
, ftAccess
);
2253 ConvertFileTimeToWx(dtMod
, ftWrite
);
2257 #elif defined(__UNIX_LIKE__) || defined(__WXMAC__) || defined(__OS2__) || (defined(__DOS__) && defined(__WATCOMC__))
2259 if ( wxStat( GetFullPath().c_str(), &stBuf
) == 0 )
2262 dtAccess
->Set(stBuf
.st_atime
);
2264 dtMod
->Set(stBuf
.st_mtime
);
2266 dtCreate
->Set(stBuf
.st_ctime
);
2270 #else // other platform
2271 wxUnusedVar(dtAccess
);
2273 wxUnusedVar(dtCreate
);
2276 wxLogSysError(_("Failed to retrieve file times for '%s'"),
2277 GetFullPath().c_str());
2282 #endif // wxUSE_DATETIME
2285 // ----------------------------------------------------------------------------
2286 // file size functions
2287 // ----------------------------------------------------------------------------
2290 wxULongLong
wxFileName::GetSize(const wxString
&filename
)
2292 if (!wxFileExists(filename
))
2293 return wxInvalidSize
;
2295 #if defined(__WXPALMOS__)
2297 return wxInvalidSize
;
2298 #elif defined(__WIN32__)
2299 wxFileHandle
f(filename
, wxFileHandle::Read
);
2301 return wxInvalidSize
;
2303 DWORD lpFileSizeHigh
;
2304 DWORD ret
= GetFileSize(f
, &lpFileSizeHigh
);
2305 if (ret
== INVALID_FILE_SIZE
)
2306 return wxInvalidSize
;
2308 // compose the low-order and high-order byte sizes
2309 return wxULongLong(ret
| (lpFileSizeHigh
<< sizeof(WORD
)*2));
2311 #else // ! __WIN32__
2314 #ifndef wxNEED_WX_UNISTD_H
2315 if (wxStat( filename
.fn_str() , &st
) != 0)
2317 if (wxStat( filename
, &st
) != 0)
2319 return wxInvalidSize
;
2320 return wxULongLong(st
.st_size
);
2325 wxString
wxFileName::GetHumanReadableSize(const wxULongLong
&bs
,
2326 const wxString
&nullsize
,
2329 static const double KILOBYTESIZE
= 1024.0;
2330 static const double MEGABYTESIZE
= 1024.0*KILOBYTESIZE
;
2331 static const double GIGABYTESIZE
= 1024.0*MEGABYTESIZE
;
2332 static const double TERABYTESIZE
= 1024.0*GIGABYTESIZE
;
2334 if (bs
== 0 || bs
== wxInvalidSize
)
2337 double bytesize
= bs
.ToDouble();
2338 if (bytesize
< KILOBYTESIZE
)
2339 return wxString::Format(_("%s B"), bs
.ToString().c_str());
2340 if (bytesize
< MEGABYTESIZE
)
2341 return wxString::Format(_("%.*f kB"), precision
, bytesize
/KILOBYTESIZE
);
2342 if (bytesize
< GIGABYTESIZE
)
2343 return wxString::Format(_("%.*f MB"), precision
, bytesize
/MEGABYTESIZE
);
2344 if (bytesize
< TERABYTESIZE
)
2345 return wxString::Format(_("%.*f GB"), precision
, bytesize
/GIGABYTESIZE
);
2347 return wxString::Format(_("%.*f TB"), precision
, bytesize
/TERABYTESIZE
);
2350 wxULongLong
wxFileName::GetSize() const
2352 return GetSize(GetFullPath());
2355 wxString
wxFileName::GetHumanReadableSize(const wxString
&failmsg
, int precision
) const
2357 return GetHumanReadableSize(GetSize(), failmsg
, precision
);
2361 // ----------------------------------------------------------------------------
2362 // Mac-specific functions
2363 // ----------------------------------------------------------------------------
2367 const short kMacExtensionMaxLength
= 16 ;
2368 class MacDefaultExtensionRecord
2371 MacDefaultExtensionRecord()
2374 m_type
= m_creator
= 0 ;
2376 MacDefaultExtensionRecord( const MacDefaultExtensionRecord
& from
)
2378 wxStrcpy( m_ext
, from
.m_ext
) ;
2379 m_type
= from
.m_type
;
2380 m_creator
= from
.m_creator
;
2382 MacDefaultExtensionRecord( const wxChar
* extension
, OSType type
, OSType creator
)
2384 wxStrncpy( m_ext
, extension
, kMacExtensionMaxLength
) ;
2385 m_ext
[kMacExtensionMaxLength
] = 0 ;
2387 m_creator
= creator
;
2389 wxChar m_ext
[kMacExtensionMaxLength
] ;
2394 WX_DECLARE_OBJARRAY(MacDefaultExtensionRecord
, MacDefaultExtensionArray
) ;
2396 bool gMacDefaultExtensionsInited
= false ;
2398 #include "wx/arrimpl.cpp"
2400 WX_DEFINE_EXPORTED_OBJARRAY(MacDefaultExtensionArray
) ;
2402 MacDefaultExtensionArray gMacDefaultExtensions
;
2404 // load the default extensions
2405 MacDefaultExtensionRecord gDefaults
[] =
2407 MacDefaultExtensionRecord( wxT("txt") , 'TEXT' , 'ttxt' ) ,
2408 MacDefaultExtensionRecord( wxT("tif") , 'TIFF' , '****' ) ,
2409 MacDefaultExtensionRecord( wxT("jpg") , 'JPEG' , '****' ) ,
2412 static void MacEnsureDefaultExtensionsLoaded()
2414 if ( !gMacDefaultExtensionsInited
)
2416 // we could load the pc exchange prefs here too
2417 for ( size_t i
= 0 ; i
< WXSIZEOF( gDefaults
) ; ++i
)
2419 gMacDefaultExtensions
.Add( gDefaults
[i
] ) ;
2421 gMacDefaultExtensionsInited
= true ;
2425 bool wxFileName::MacSetTypeAndCreator( wxUint32 type
, wxUint32 creator
)
2428 FSCatalogInfo catInfo
;
2431 if ( wxMacPathToFSRef( GetFullPath() , &fsRef
) == noErr
)
2433 if ( FSGetCatalogInfo (&fsRef
, kFSCatInfoFinderInfo
, &catInfo
, NULL
, NULL
, NULL
) == noErr
)
2435 finfo
= (FileInfo
*)&catInfo
.finderInfo
;
2436 finfo
->fileType
= type
;
2437 finfo
->fileCreator
= creator
;
2438 FSSetCatalogInfo( &fsRef
, kFSCatInfoFinderInfo
, &catInfo
) ;
2445 bool wxFileName::MacGetTypeAndCreator( wxUint32
*type
, wxUint32
*creator
)
2448 FSCatalogInfo catInfo
;
2451 if ( wxMacPathToFSRef( GetFullPath() , &fsRef
) == noErr
)
2453 if ( FSGetCatalogInfo (&fsRef
, kFSCatInfoFinderInfo
, &catInfo
, NULL
, NULL
, NULL
) == noErr
)
2455 finfo
= (FileInfo
*)&catInfo
.finderInfo
;
2456 *type
= finfo
->fileType
;
2457 *creator
= finfo
->fileCreator
;
2464 bool wxFileName::MacSetDefaultTypeAndCreator()
2466 wxUint32 type
, creator
;
2467 if ( wxFileName::MacFindDefaultTypeAndCreator(GetExt() , &type
,
2470 return MacSetTypeAndCreator( type
, creator
) ;
2475 bool wxFileName::MacFindDefaultTypeAndCreator( const wxString
& ext
, wxUint32
*type
, wxUint32
*creator
)
2477 MacEnsureDefaultExtensionsLoaded() ;
2478 wxString extl
= ext
.Lower() ;
2479 for( int i
= gMacDefaultExtensions
.Count() - 1 ; i
>= 0 ; --i
)
2481 if ( gMacDefaultExtensions
.Item(i
).m_ext
== extl
)
2483 *type
= gMacDefaultExtensions
.Item(i
).m_type
;
2484 *creator
= gMacDefaultExtensions
.Item(i
).m_creator
;
2491 void wxFileName::MacRegisterDefaultTypeAndCreator( const wxString
& ext
, wxUint32 type
, wxUint32 creator
)
2493 MacEnsureDefaultExtensionsLoaded() ;
2494 MacDefaultExtensionRecord rec
;
2496 rec
.m_creator
= creator
;
2497 wxStrncpy( rec
.m_ext
, ext
.Lower().c_str() , kMacExtensionMaxLength
) ;
2498 gMacDefaultExtensions
.Add( rec
) ;