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

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

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

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

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

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

例子

  1. Input | Output
  2. ---------------------------------
  3. C:\path\to\file -> C:\path\to\
  4. C:\path\to\file.c -> C:\path\to\
  5. C:\file -> C:\
  6. .\file -> .\
  7. .\ -> .\
  8. \ -> \

参考

> Extract file name from full path in C using MSVS2005

解决方法

在Windows上有 _splitpath.

  1. #include <Windows.h>
  2. #include <tchar.h>
  3.  
  4. // Use your own error codes here
  5. #define SUCCESS 0L
  6. #define FAILURE_NULL_ARGUMENT 1L
  7. #define FAILURE_API_CALL 2L
  8. #define FAILURE_INSUFFICIENT_BUFFER 3L
  9.  
  10. DWORD GetBasePathFromPathName( LPCTSTR szPathName,LPTSTR szBasePath,DWORD dwBasePathSize )
  11. {
  12. TCHAR szDrive[_MAX_DRIVE] = { 0 };
  13. TCHAR szDir[_MAX_DIR] = { 0 };
  14. TCHAR szFname[_MAX_FNAME] = { 0 };
  15. TCHAR szExt[_MAX_EXT] = { 0 };
  16. size_t PathLength;
  17. DWORD dwReturnCode;
  18.  
  19. // Parameter validation
  20. if( szPathName == NULL || szBasePath == NULL )
  21. {
  22. return FAILURE_NULL_ARGUMENT;
  23. }
  24.  
  25. // Split the path into it's components
  26. dwReturnCode = _tsplitpath_s( szPathName,szDrive,_MAX_DRIVE,szDir,_MAX_DIR,szFname,_MAX_FNAME,szExt,_MAX_EXT );
  27. if( dwReturnCode != 0 )
  28. {
  29. _ftprintf( stderr,TEXT("Error splitting path. _tsplitpath_s returned %d.\n"),dwReturnCode );
  30. return FAILURE_API_CALL;
  31. }
  32.  
  33. // Check that the provided buffer is large enough to store the results and a terminal null character
  34. PathLength = _tcslen( szDrive ) + _tcslen( szDir );
  35. if( ( PathLength + sizeof( TCHAR ) ) > dwBasePathSize )
  36. {
  37. _ftprintf( stderr,TEXT("Insufficient buffer. required %d. Provided: %d\n"),PathLength,dwBasePathSize );
  38. return FAILURE_INSUFFICIENT_BUFFER;
  39. }
  40.  
  41. // Copy the szDrive and szDir into the provide buffer to form the basepath
  42. if( ( dwReturnCode = _tcscpy_s( szBasePath,dwBasePathSize,szDrive ) ) != 0 )
  43. {
  44. _ftprintf( stderr,TEXT("Error copying string. _tcscpy_s returned %d\n"),dwReturnCode );
  45. return FAILURE_API_CALL;
  46. }
  47. if( ( dwReturnCode = _tcscat_s( szBasePath,szDir ) ) != 0 )
  48. {
  49. _ftprintf( stderr,TEXT("Error copying string. _tcscat_s returned %d\n"),dwReturnCode );
  50. return FAILURE_API_CALL;
  51. }
  52. return SUCCESS;
  53. }

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