Click here to Skip to main content
14,022,607 members
Click here to Skip to main content
Add your own
alternative version


87 bookmarked
Posted 6 Aug 2002

CPath 1.2 - To work with path strings easily

, 15 Aug 2002
Rate this:
Please Sign up or sign in to vote.
A class to work with path strings, to parse command line arguments and get file properties

Sample Image - image.gif


  • Current version: 1.2
  • CPath requires linking with the library shlwapi.lib

What can I do with this class?

  • Splitting a path string into its components
  • Command line parameters parsing
  • Converting a relative path in absolute and the other way around
  • Getting the properties of a file (size & dates)
  • and more!

How do I start using this class?

  • calling the SetPath method
  • constructing the object using one of the two overloaded constructors, with take the same parameters as the two versions of SetPath.
  • using the assignment operator

The class handles not only local but also network and relative paths.

// Calling the SetPath method
CPath path1;

// Using an overloaded constructor
CPath path2("\\\\servername\\temp\\file.txt");

// Using the asignment operator
CPath path3;
path3 = "c:\\temp\\file.txt";

The SetPath method and overloaded constructors

CPath(LPCTSTR szPath, BOOL bIsFolderPath = FALSE, BOOL bHasArguments = FALSE)

void SetPath(LPCTSTR szPath, BOOL bIsFolderPath = FALSE, BOOL bHasArguments = FALSE)

  • szPath is a null terminated string containing the path.
  • bIsFolderPath must be set to TRUE if we know szPath represents a folder path but we are not sure if it's terminated with a slash or back slash character ('/' or '\'). And why is this necessary? Well, imagine you pass the string "c:\\temp\\subfolder" to this method. If bIsFolderPath is not set to TRUE, the class interprets that "subfolder" is a file name with no extension.
  • bHasArguments will be set to TRUE if the szPath string includes arguments. If that's the case but HasArguments is not set to TRUE, the path will not be properly split / parsed.

CPath(DWORD dwSpecial) / void SetPath(DWORD dwSpecial)

  • dwSpecial can take one of the following values:
    • PATH_CMDLINE - Set the path and arguments to the value returned by GetCommandLine(). (The GetCommandLine function returns a pointer to the command-line string for the current process)
    • PATH_MODULE - Set the path to the value returned from GetModuleFileName with hModule set to NULL. (If this parameter is NULL, GetModuleFileName returns the path for the file used to create the calling process)

What do I get exactly from each one of the Get... functions?

We will see this with examples, because it's something very easy to understand but very difficult to explain. The paths bellow will be used:

  1. c:\folder\subfolder\localfile.ext
  2. \\server\folder\netfile.ext
  3. ..\images\picture.jpg
Function Return value 1 Return value 2 Return value 3
GetDrive c:    
GetDir \folder\subfolder\ \\server\folder\ ..\images\
GetDirCount 2 2 2
GetLocation c:\folder\subfolder\ \\server\folder\ ..\images\
GetFileName localfile.ext netfile.ext picture.jpg
GetFileTitle localfile netfile picture
GetExtension .ext .ext .jpg
GetExtName ext ext jpg

CString GetPath(BOOL bAppendArgs = FALSE, BOOL bOriginal = FALSE)

Return the path contained in the object. If bAppendArgs is TRUE, the arguments are appended (if any). If bOriginal is TRUE, the same string that was passed to SetPath or the constructor is returned.

CString GetShortPath() / CString GetLongPath()

Return the short and long form versions of the path. If the file or folder doesn't exist the returned CString will be empty.

Getting other information

CString GetDriveLabel(BOOL bPCNameIfNetwork = FALSE)

Return the label of the drive or empty if the drive unit doesn't exist. If bPCNameIfNetwork is TRUE and the path is a network one, the return value will be the name of the server.

BOOL GetFileSize(__int64 &nSize)

The size of the file or 0 if the path is a folder path or the file doesn't exist.

BOOL GetFileTime(CTime &time, DWORD dwType = FILE_WRITE)

A CTime object with the file creation time (FILE_CREATION), last write time (FILE_WRITE) or last access time (FILE_ACCESS).

BOOL IsLocalPath()

Return TRUE if the path is a local path. FALSE for network and relative paths.

BOOL IsRelativePath()

Return TRUE for relative paths.

BOOL IsFilePath()

Return TRUE for paths including a file name.

BOOL ExistFile()

Return TRUE if the file exists. If IsFilePath returns FALSE, this method will return TRUE as well.

BOOL ExistLocation()

Return TRUE if the location exists. See GetLocation.


operator LPCTSTR ()

Return a temporary character pointer to the path data. Don't store this pointer, if you will need this value later in your code, make a copy of the string pointed by it

// You can use it as a parameter in a call to another function ...
CPath path("c:\\folder\\file.txt");
SomFunction(32, (LPCTSTR) path);

// ... or to make a copy
CString s;
s = path;

const CPath& operator = (LPCTSTR szPath)

The same as SetPath(szPath). See the SetPath method and overloaded constructors.

const CPath& operator = (CPath &ref)

Make a copy of the ref object in the left one.

CPath path1("c:\\folder\\file.txt"), path2;
path2 = path1;

// Now path2 has the same data as path1

Arguments stuff

CPath parses arguments with or without flags, flags without argument and recognizes arguments containing blank spaces enclosed between quotes. Let's see this with an example using the following arguments:

-s /f 2510 nfparam1 -list "c:\a folder\file.lst" nfparam2

Index Flag Argument
0 s  
1 f 2510
2   nfparam1
3 list c:\a folder\file.lst
4   nfparam2

CString GetArgument(int nIndex = -1, BOOL bGetFlag = FALSE)

Return the 0 based nIndex argument string. If nIndex = -1 the return string is the argument part of the path. If GetFlag is TRUE, return the 0 based nIndex argument flag

int FindArgument(LPCTSTR szFlag)

Return the 0 based index of the argument whose flag matches szFlag. If the flag is not found, the return value is -1

int GetArgCount()

Return the number of arguments.

void SetArguments(LPCTSTR szArgs)

Set the arguments for the current file path. (Tip: You can pass "" to reset this value).

CPath path;
CString str;

path = "c:\\folder\\app.exe";
path.SetArguments("/type 5 /skin \"blue force\" go");
str = path.GetPath(TRUE);
// str equals now  c:\folder\app.exe /type 5 /skin "blue force" go

void AddSetArgument(LPCTSTR szFlag, LPCTSTR szArgument)

Add a new argument with flag or without it if szFlag is "" or NULL. Or just a flag, or switcher. The parameter szFlag can be prefixed by '/' and '-'. If none of these two characters are found, the flag indicator defaults to '/'.

CPath path("c:\\folder\\app.exe");
CString str;

path.AddArgument("-x", NULL);
path.AddArgument("file", "c:\\My Folder\\list.txt");

str = path.GetPath(TRUE);
// str equals now  c:\folder\app.exe -x /file "c:\\My Folder\list.txt"

Relative path methods

CString GetAbsolutePath(LPCTSTR szBaseFolder)

If the path in the CPath object is not a relative path, the return CString will be empty. Otherwise, the result of properly combining the path in CPath using szBaseFolder as the root path.

CPath path("..\\images\\picture.jpg");
CString str;
str = path.GetAbsolutePath("c:\\projects\\doc");
// str is now  c:\projects\images\picture.jpg

CString GetRelativePath(LPCTSTR szBaseFolder)

If the path in the CPath object is a relative path, the return CString will be empty. Otherwise, the relative path of the value in CPath taking szBaseFolder as the root path.

CPath path("c:\\projects\\images\\picture.jpg");
CString str;
str = path.GetRelativePath("c:\\projects\\doc");
// str is now  ..\images\picture.jpg

Back slash static methods

static CString AddBackSlash(LPCTSTR szFolderPath, BOOL bInverted = FALSE)

Append a back slash ('\' or '/' if bInverted is TRUE) to szFolderPath if it's not found.

static CString RemoveBackSlash(LPCTSTR szFolderPath)

Removes a trailing back slash (or normal slash) if found at the end of szFolderPath


Version 1.2

  • Removed a call to AfxMessageBox for debug.
  • Bug in RemoveBackSlash fixed (&& replaced with ||)
  • GetFileSize and GetFileTime redefined to return a boolean.
  • Arguments handling routines improved.
  • Added AddSetArgument and RemoveArgument methods.
  • Both operator = return now a constant reference to itself (const CPath&).


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author

Samuel Gonzalo
Software Developer (Senior)
Spain Spain
I studied Telecommunication with spezialization in Sound & Image. I was always very interested in programming at university as well and that is how I earn a living.

Since some years ago, I am also succesfully involved in software architecture and design.

You may also be interested in...

Comments and Discussions

GeneralsCEmptyString bug in CPath Pin
Jean-Marc Dressler18-Nov-07 8:52
memberJean-Marc Dressler18-Nov-07 8:52 
GeneralBug in GetRelativePath Pin
mykel18-Oct-06 10:49
membermykel18-Oct-06 10:49 
GeneralMFC dependency Pin
sdaymond4-Jan-06 1:27
membersdaymond4-Jan-06 1:27 
GeneralMany thanks from a newbie... Pin
vanstac17-Nov-04 18:15
membervanstac17-Nov-04 18:15 
GeneralApplication Path Pin
Anonymous15-Sep-04 8:27
memberAnonymous15-Sep-04 8:27 
GeneralRe: Application Path Pin
Samuel Gonzalo15-Sep-04 21:22
memberSamuel Gonzalo15-Sep-04 21:22 
GeneralIs anyone intersted in TCHAR (unicode) version of the class Pin
daniel_zy5-Sep-04 4:14
memberdaniel_zy5-Sep-04 4:14 
GeneralDot in the path Pin
mykel24-Feb-04 0:04
membermykel24-Feb-04 0:04 
GeneralRe: Dot in the path Pin
Samuel Gonzalo22-Mar-04 6:19
memberSamuel Gonzalo22-Mar-04 6:19 
GeneralRe: Dot in the path Pin
Samuel Gonzalo22-Mar-04 6:22
memberSamuel Gonzalo22-Mar-04 6:22 
GeneralRe: Dot in the path Pin
mykel14-May-04 0:56
membermykel14-May-04 0:56 
Generalfile time difference with windows Pin
Muhammad Ahmed20-Feb-04 0:45
memberMuhammad Ahmed20-Feb-04 0:45 
GeneralRe: file time difference with windows Pin
Samuel Gonzalo22-Mar-04 6:02
memberSamuel Gonzalo22-Mar-04 6:02 
GeneralThe wheel has been reinvented Pin
bouli14-Nov-03 2:14
memberbouli14-Nov-03 2:14 
GeneralRe: The wheel has been reinvented Pin
Samuel Gonzalo14-Nov-03 14:23
memberSamuel Gonzalo14-Nov-03 14:23 
GeneralRe: The wheel has been reinvented Pin
peterchen28-Oct-04 23:56
memberpeterchen28-Oct-04 23:56 
GeneralRe: The wheel* - Pin
Gorskiy29-Jul-05 23:35
memberGorskiy29-Jul-05 23:35 
GeneralClarification... Pin
raghu_try3-Oct-03 0:11
memberraghu_try3-Oct-03 0:11 
GeneralRe: Clarification... Pin
Samuel Gonzalo3-Oct-03 16:59
memberSamuel Gonzalo3-Oct-03 16:59 
QuestionCompile Error ????? Pin
Member 7413985-Nov-02 17:45
memberMember 7413985-Nov-02 17:45 
AnswerRe: Compile Error ????? Pin
Christian Graus5-Nov-02 17:56
protectorChristian Graus5-Nov-02 17:56 
AnswerRe: Compile Error ????? Pin
toun495-Nov-02 17:51
membertoun495-Nov-02 17:51 
GeneralThanks ! Pin
YoSilver24-Oct-02 14:38
memberYoSilver24-Oct-02 14:38 
GeneralAddBackslash not DBCS safe Pin
Michael Dunn17-Aug-02 11:30
sitebuilderMichael Dunn17-Aug-02 11:30 
GeneralThanks a lot for your prompt update! Pin
TeleStar16-Aug-02 17:44
memberTeleStar16-Aug-02 17:44 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web01 | 2.8.190417.4 | Last Updated 16 Aug 2002
Article Copyright 2002 by Samuel Gonzalo
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid