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

Zac*_*ame 6 c windows file

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

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

我问这个问题基本上是相反的.

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

例子

Input              | Output
---------------------------------
C:\path\to\file   -> C:\path\to\
C:\path\to\file.c -> C:\path\to\
C:\file           -> C:\
.\file            -> .\
.\                -> .\
\                 -> \
Run Code Online (Sandbox Code Playgroud)

参考

and*_*ski 6

在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, dwBasePathSize, szDir ) ) != 0 )
  {
    _ftprintf( stderr, TEXT("Error copying string. _tcscat_s returned %d\n"), dwReturnCode );
    return FAILURE_API_CALL;
  }
  return SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)


Dav*_*nan 5

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

不是,没有。路径名的规则是特定于平台的,因此标准不涵盖它们。