C/C ++ file path Parsing
First, let's take a look at the path parsing and merging functions in C/C ++._splitpathAnd_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);
Don't be scared by complicated function declarations. It's actually very easy.
For_splitpathPath parsing functions:
_FullPath: Full path (
input)
_Drive: Drive letter (
output)
_Dir: Remove the intermediate path of the drive letter and file name (
output)
_Filename: File Name (
output)
_Ext: Extended name (
output)
For_makepathPath synthesis function. The preceding parameters have the same meaning, but the input and output are the opposite.
A sample code is provided:
#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.cPath extracted with _splitpath: _Drive: c: _Dir: \sample\file\ _Filename: makepath _Ext: .c
Some macros are defined as follows:
/* * 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 */
Sometimes, we only need to get the file name or extension name, so using the above method is a bit cumbersome,stringType and its operation functions can be easily implemented:
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
Similarly, if you want to use this method to get the file name, you only needfilePath.find_last_of(".")ChangefilePath.find_last_of("\\")In addition, we usetransformFunction, where the parameterstolowerIf the character has a lower-case character, it is converted to a lower-case character.