Click here to Skip to main content
Click here to Skip to main content
Go to top

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

Introduction

  • 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;
path1.SetPath("c:\\temp\\file.txt");

// 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.

Operators

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

History

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&).

License

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

Share

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.

Comments and Discussions

 
GeneralsCEmptyString bug in CPath PinmemberJean-Marc Dressler18-Nov-07 8:52 
GeneralBug in GetRelativePath Pinmembermykel18-Oct-06 10:49 
GeneralMFC dependency Pinmembersdaymond4-Jan-06 1:27 
GeneralMany thanks from a newbie... Pinmembervanstac17-Nov-04 18:15 
GeneralApplication Path PinsussAnonymous15-Sep-04 8:27 
GeneralRe: Application Path PinmemberSamuel Gonzalo15-Sep-04 21:22 
GeneralIs anyone intersted in TCHAR (unicode) version of the class Pinsussdaniel_zy5-Sep-04 4:14 
GeneralDot in the path PinmembermYkel24-Feb-04 0:04 
GeneralRe: Dot in the path PinmemberSamuel Gonzalo22-Mar-04 6:19 
GeneralRe: Dot in the path PinmemberSamuel Gonzalo22-Mar-04 6:22 
GeneralRe: Dot in the path PinmembermYkel14-May-04 0:56 
Generalfile time difference with windows PinmemberMuhammad Ahmed20-Feb-04 0:45 
GeneralRe: file time difference with windows PinmemberSamuel Gonzalo22-Mar-04 6:02 
GeneralThe wheel has been reinvented Pinmemberbouli14-Nov-03 2:14 
GeneralRe: The wheel has been reinvented PinmemberSamuel Gonzalo14-Nov-03 14:23 
GeneralRe: The wheel has been reinvented Pinmemberpeterchen28-Oct-04 23:56 
GeneralRe: The wheel* - PinsussGorskiy29-Jul-05 23:35 
GeneralClarification... Pinmemberraghu_try3-Oct-03 0:11 
GeneralRe: Clarification... PinmemberSamuel Gonzalo3-Oct-03 16:59 
QuestionCompile Error ????? PinsussMod_x5-Nov-02 17:45 
AnswerRe: Compile Error ????? PinmemberChristian Graus5-Nov-02 17:56 
AnswerRe: Compile Error ????? Pinsusstoun5-Nov-02 17:51 
GeneralThanks ! PinmemberYoSilver24-Oct-02 14:38 
GeneralAddBackslash not DBCS safe PinsitebuilderMichael Dunn17-Aug-02 11:30 
GeneralThanks a lot for your prompt update! Pinmemberxxxyyyzzz16-Aug-02 17:44 

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

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

| Advertise | Privacy | Mobile
Web02 | 2.8.140922.1 | Last Updated 16 Aug 2002
Article Copyright 2002 by Samuel Gonzalo
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid