首先,看一下C/C++中的路徑解析與合成的兩個函數_splitpath
與_makepath
:
_CRT_INSECURE_DEPRECATE(_splitpath_s) _CRTIMP void __cdecl _splitpath(_In_z_ const char * _FullPath, _Pre_maybenull_ _Post_z_ char * _Drive, _Pre_maybenull_ _Post_z_ char * _Dir, _Pre_maybenull_ _Post_z_ char * _Filename, _Pre_maybenull_ _Post_z_ char * _Ext);
void __cdecl _makepath(char* _Path, const char* _Drive, const char* _Dir, const char* _Filename, const char* _Ext);
不要被復雜的函數聲明給嚇到,其實很簡單。
對於_splitpath
路徑解析函數:
_FullPath
: 全路徑(input
) _Drive
: 盤符(output
) _Dir
: 除去盤符和文件名的中間路徑(output
) _Filename
:文件名(output
) _Ext
:拓展名(output
)
對於_makepath
路徑合成函數,上述的參數含義相同,只是輸入與輸出相反。
給出一段代碼示例:
#include
#include
void main( void )
{
char full_path[_MAX_PATH];
char drive[_MAX_DRIVE];
char dir[_MAX_DIR];
char fname[_MAX_FNAME];
char ext[_MAX_EXT];
_makepath( full_path, "c", "\\sample\\file\\", "makepath", "c" );
printf( "_FullPath created with _makepath: %s\n\n", full_path);
_splitpath( full_path, drive, dir, fname, ext );
printf( "Path extracted with _splitpath:\n" );
printf( " _Drive: %s\n", drive );
printf( " _Dir: %s\n", dir );
printf( " _Filename: %s\n", fname );
printf( " _Ext: %s\n", ext );
}
// Output
_FullPath created with _makepath: c:\sample\file\makepath.c
Path extracted with _splitpath:
_Drive: c:
_Dir: \sample\file\
_Filename: makepath
_Ext: .c
其中的一些宏定義如下:
/*
* Sizes for buffers used by the _makepath() and _splitpath() functions.
* note that the sizes include space for 0-terminator
*/
#define _MAX_PATH 260 /* max. length of full pathname */
#define _MAX_DRIVE 3 /* max. length of drive component */
#define _MAX_DIR 256 /* max. length of path component */
#define _MAX_FNAME 256 /* max. length of file name component */
#define _MAX_EXT 256 /* max. length of extension component */
有時候,我們僅需要獲得文件的文件名或者拓展名,那麼用上述的方法就有點繁瑣,string
類型及其操作函數就能很方便地實現:
string filePath = "E:\\file\\main.cpp";
string extendName;
int iBeginIndex = filePath.find_last_of(".")+1;
int iEndIndex = filePath.length();
extendName = filePath.substr( iBeginIndex, iEndIndex-iBeginIndex );
transform( extendName.begin(), extendName.end(), extendName.begin(), tolower );
cout << extendName << endl;
// Output : cpp
同理,如果想用該方法獲取文件名,只需將filePath.find_last_of(".")
修改為filePath.find_last_of("\\")
,另外,這裡為了使輸出的文件拓展名一致,使用了transform
函數,其中的參數tolower
,含義是如果該字符有對應的小寫字符,則轉為小寫字符。