Posts tagged File path

How to parse the parent directory from a given path – More easily?

0


Yesterday one of my friend called me to solve the mystery behind his crash! When i checked the code, i saw a couple of string operations by pointers, memory allocations, memset - All evils under one hood. :) Actually the memset caused the crash which writes beyond the buffer and corrupt other stack objects.

But suddenly i noticed one thing – what he is trying to do? He have a path and he wants to get the parent path. E.g. If his path is “C:\Application\Config”, then he want to get - “C:\Application” the just parent path. Well, the guy brushed up old string lessons and handled everything by himself which resulted in crash. I reviled him a secret api to do the stuff painlessly. Mmmm… I can tell that secret to you too…


The api is – PathRemoveFileSpec(). You can use it to remove the last directory or filename from the given path. Have a look at the code snippet.

#include "Shlwapi.h"
...
// Main path.
TCHAR pBinPath[] = _T("C:\\MyApplication\\bin");

// Get the parent path.
PathRemoveFileSpec( pBinPath );

// Now the pBinPath contains - "C:\\MyApplication"


Don’t forget to add Shlwapi.lib to project settings. ;)


Targeted Audience – Beginners.

How to check whether a file exists of not?

2


While reading configuration file, while reading some setting file, every where we’ve to check whether the file exists or not before opening and starts reading. The simple technique is to open the file by using file apis or to search for the file by using FindFirstFile(). Or is there any simple api to do so?


You can use the api – PathFileExists(). Check the following code snippet.

#include "shlwapi.h"
...
// File path.
CString csFile = _T( "C:\\Autumn Leaves.jpg");

if( PathFileExists( csFile ))
{
    // Yes! the file exists.
}


Don’t forget to add shlwapi.lib to your project settings. ;)


Targeted Audience – Beginners.

Go to Top