One splitpath implementation (platform independent)


#include "stdio.h"

#include "stdlib.h"
#include 
"wchar.h"

typedef wchar_t WCHAR;

void _wsplitpath(const WCHAR* path, WCHAR* drv, WCHAR* dir, WCHAR* name, WCHAR* ext)
{
    
const WCHAR* end; /* end of processed string */
    
const WCHAR* p;      /* search pointer */
    
const WCHAR* s;      /* copy pointer */
    
    
/* extract drive name */
    
if (path[0&& path[1]==':') {
        
if (drv) {
            
*drv++ = *path++;
            
*drv++ = *path++;
            
*drv = '\0';
        }
    } 
else if (drv)
        
*drv = '\0';
    
    
/* search for end of string or stream separator */
    
for(end=path; *end && *end!=':'; )
        end
++;
    
    
/* search for begin of file extension */
    
for(p=end; p>path && *--p!='\\' && *p!='/'; )
        
if (*== '.') {
            end 
= p;
            
break;
        }
    
    
if (ext)
        
for(s=end; (*ext=*s++); )
            ext
++;
    
    
/* search for end of directory name */
    
for(p=end; p>path; )
        
if (*--p=='\\' || *p=='/') {
            p
++;
            
break;
        }
    
    
if (name) {
        
for(s=p; s<end; )
            
*name++ = *s++;
        
        
*name = '\0';
    }
    
    
if (dir) {
        
for(s=path; s<p; )
            
*dir++ = *s++;
        
        
*dir = '\0';
    }
}

#define _MAX_DRIVE 255
#define _MAX_DIR 255
#define _MAX_FNAME 255
#define _MAX_EXT 255

int main()    // test splipath()
{
    wchar_t drv[_MAX_DRIVE
+1], dir[_MAX_DIR], name[_MAX_FNAME], ext[_MAX_EXT];
    
    _wsplitpath(L
"/Perforce/sandbox/flower.jpg", drv, dir, name, ext);
    wprintf(L
"drv = %S, dir = %S, filename = %S, ext = %S \n", drv, dir, name, ext);
    _wsplitpath(L
"C:\\Program files\\sandbox\\flower.jpg", drv, dir, name, ext);
    wprintf(L
"drv = %S, dir = %S, filename = %S, ext = %S \n", drv, dir, name, ext);
    _wsplitpath(L
"\\x", drv, dir, name, ext);
    _wsplitpath(L
"x", drv, dir, name, ext);
    _wsplitpath(L
"", drv, dir, name, ext);
    _wsplitpath(L
".x", drv, dir, name, ext);
    _wsplitpath(L
":x", drv, dir, name, ext);
    _wsplitpath(L
"a:x", drv, dir, name, ext);
    _wsplitpath(L
"a.b:x", drv, dir, name, ext);
    _wsplitpath(L
"W:\\/\\abc/Z:~", drv, dir, name, ext);
    _wsplitpath(L
"abc.EFGH:12345", drv, dir, name, ext);
    _wsplitpath(L
"C:/dos/command.com", drv, dir, name, ext);
    
    
return 0;
}

posted on 2008-08-07 13:59  SunWentao  阅读(576)  评论(1编辑  收藏  举报