Many times I have had the need to split a path into its components (who hasn't?). And every
time I needed to do this I would use the venerable _splitpath()
command. I often
wondered why there isn't a class wrapper for this function. So here it is, CSplitPath
.
It's pretty much self-explanatory: Create an instance of the class with the path to split in
the constructor. Then use the member functions to get the pieces you want.
It's that simple. Enjoy!
CSplitPath sp( "C:\\Temp\\Foo.txt" );
cout << "Drive: " << sp.GetDrive()
cout << "Directory: " << sp.GetDirectory();
cout << "File Name: " << sp.GetFileName();
cout << "Extension: " << sp.GetExtension();
The source code is very small and is as follows:
#ifndef __SPLITPATH_H__
#define __SPLITPATH_H__
#if _MSC_VER >= 1000
#pragma once
#endif // _MSC_VER >= 1000
class CSplitPath
{
public:
CSplitPath( LPCTSTR lpszPath = NULL );
BOOL Split(LPCTSTR lpszPath );
CString GetPath( void ) { return path_buffer; }
CString GetDrive( void ) { return drive; }
CString GetDirectory( void ) { return dir; }
CString GetFileName( void ) { return fname; }
CString GetExtension( void ) { return ext; }
protected:
TCHAR path_buffer[_MAX_PATH];
TCHAR drive[_MAX_DRIVE];
TCHAR dir[_MAX_DIR];
TCHAR fname[_MAX_FNAME];
TCHAR ext[_MAX_EXT];
};
#endif // __SPLITPATH_H__
#include "stdafx.h"
#include "SplitPath.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
CSplitPath::CSplitPath( LPCTSTR lpszPath )
{
memset( path_buffer, 0, sizeof( path_buffer ) );
memset( drive, 0, sizeof( drive ) );
memset( dir, 0, sizeof( dir ) );
memset( fname, 0, sizeof( fname ) );
memset( ext, 0, sizeof( ext ) );
if ( lpszPath ) {
Split( lpszPath );
}
}
BOOL CSplitPath::Split( LPCTSTR lpszPath )
{
if ( lpszPath == NULL ) {
return FALSE;
}
_tcsncpy( path_buffer, lpszPath, sizeof( path_buffer ) - 1 );
_tsplitpath( path_buffer, drive, dir, fname, ext );
return TRUE;
}
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.