从C中的路径名中提取基本路径

前端之家收集整理的这篇文章主要介绍了从C中的路径名中提取基本路径前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

如何从C中的路径名中提取基本路径?

C语言或C运行时库中是否有任何函数可以从C中的路径名中提取基本路径?

我问基本上与this问题相反.

注意:我更喜欢跨平台解决方案,但我在Windows中工作,所以如果有一个Windows API调用这样做,我仍然想知道.

例子

Input              | Output
---------------------------------
C:\path\to\file   -> C:\path\to\
C:\path\to\file.c -> C:\path\to\
C:\file           -> C:\
.\file            -> .\
.\                -> .\
\                 -> \

参考

> Extract file name from full path in C using MSVS2005

解决方法

在Windows上有 _splitpath.

#include <Windows.h>
#include <tchar.h>

// Use your own error codes here
#define SUCCESS                     0L
#define FAILURE_NULL_ARGUMENT       1L
#define FAILURE_API_CALL            2L
#define FAILURE_INSUFFICIENT_BUFFER 3L

DWORD GetBasePathFromPathName( LPCTSTR szPathName,LPTSTR  szBasePath,DWORD   dwBasePathSize )
{
  TCHAR   szDrive[_MAX_DRIVE] = { 0 };
  TCHAR   szDir[_MAX_DIR]     = { 0 };
  TCHAR   szFname[_MAX_FNAME] = { 0 };
  TCHAR   szExt[_MAX_EXT]     = { 0 };
  size_t  PathLength;
  DWORD   dwReturnCode;

  // Parameter validation
  if( szPathName == NULL || szBasePath == NULL )
  {
    return FAILURE_NULL_ARGUMENT;
  }

  // Split the path into it's components
  dwReturnCode = _tsplitpath_s( szPathName,szDrive,_MAX_DRIVE,szDir,_MAX_DIR,szFname,_MAX_FNAME,szExt,_MAX_EXT );
  if( dwReturnCode != 0 )
  {
    _ftprintf( stderr,TEXT("Error splitting path. _tsplitpath_s returned %d.\n"),dwReturnCode );
    return FAILURE_API_CALL;
  }

  // Check that the provided buffer is large enough to store the results and a terminal null character
  PathLength = _tcslen( szDrive ) + _tcslen( szDir );
  if( ( PathLength + sizeof( TCHAR ) ) > dwBasePathSize )
  {
    _ftprintf( stderr,TEXT("Insufficient buffer. required %d. Provided: %d\n"),PathLength,dwBasePathSize );
    return FAILURE_INSUFFICIENT_BUFFER;
  }

  // Copy the szDrive and szDir into the provide buffer to form the basepath
  if( ( dwReturnCode = _tcscpy_s( szBasePath,dwBasePathSize,szDrive ) ) != 0 )
  {
    _ftprintf( stderr,TEXT("Error copying string. _tcscpy_s returned %d\n"),dwReturnCode );
    return FAILURE_API_CALL;
  }
  if( ( dwReturnCode = _tcscat_s( szBasePath,szDir ) ) != 0 )
  {
    _ftprintf( stderr,TEXT("Error copying string. _tcscat_s returned %d\n"),dwReturnCode );
    return FAILURE_API_CALL;
  }
  return SUCCESS;
}

猜你在找的C&C++相关文章