4 out of 9 rated this helpful - Rate this topic

PathRemoveFileSpec function

Applies to: desktop apps only

Removes the trailing file name and backslash from a path, if they are present.

Syntax

BOOL PathRemoveFileSpec(
  __inout  LPTSTR pszPath
);

Parameters

pszPath [in, out]

Type: LPTSTR

A pointer to a null-terminated string of length MAX_PATH that contains the path from which to remove the file name.

Return value

Type: BOOL

Returns nonzero if something was removed, or zero otherwise.

Examples


#include <windows.h>
#include <iostream.h>
#include "Shlwapi.h"

void main( void )
{
// Path to include file spec.
char buffer_1[ ] = "C:\\TEST\\sample.txt"; 
char *lpStr1;
lpStr1 = buffer_1;

// Print the path with the file spec.
cout << "The path with file spec is          : " << lpStr1 << endl;

// Call to "PathRemoveFileSpec".
PathRemoveFileSpec(lpStr1);

// Print the path without the file spec.
cout << "\nThe path without file spec is       : " << lpStr1 << endl;
}

OUTPUT:
==================
The path with file spec is          : C:\TEST\sample.txt

The path without file spec is       : C:\TEST

Requirements

Minimum supported client

Windows 2000 Professional, Windows XP

Minimum supported server

Windows 2000 Server

Header

Shlwapi.h

Library

Shlwapi.lib

DLL

Shlwapi.dll (version 4.71 or later)

Unicode and ANSI names

PathRemoveFileSpecW (Unicode) and PathRemoveFileSpecA (ANSI)

 

 

Send comments about this topic to Microsoft

Build date: 3/7/2012

Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
Corner cases

The documentation doesn't mention how some corner cases are handled. Following are some results on XP with SP3 using the ASCII version:

C:\mydir -> C:\
C:mydir -> C:
C:mydir\data -> C:mydir
\mydir -> \
mydir -> (empty string)
C:\ -> C:\ (unchanged)
\ -> \ (unchanged)

In other words, the function behaves correctly by not removing the backslash if it appears to indicate the root directory, so it's safe to use it on path names that refer to a file or directory in the root directory.

As Thomas Lee noted, forward slashes are not supported by this function. This is probably a bug: forward slashes have been allowed in most other functions as path separators since the DOS days. Apparently this function sees them as part of the path name, not as separator. Some more examples to illustrate:

C:\mydir/data -> C:\
C:/mydir/data -> C:
C:/mydir\data -> C:/mydir
MAX_PATH no longer a limitation
Not sure when this change happened, but it appears that MAX_PATH (260 in multi-byte characters) is no longer a limitation to this function.  I passed a 339-character length string to the function, and it returned the expected path..
Do not use on paths containing forward slashes
I've tried using this on a path such as:

c:\something/noticethat/file.data

And it will not work as expected in this case.