Removing the trailing file name and backslash from a path

Sometimes we would like to remove the trailing file name and backslash from a path. In the following, there are several different ways  to make it and I am glad to share with you.

[1] MFC下的方法,使用CString类的ReserveFind、Left成员函数。
CString strPath = T("C://TEST//sample.txt"); int n = strPath.ReserveFind(_T('//')); strPath = strPath.Left(n + 1);

[2] C的方法,使用strrchr逆向字符串查找函数。

#include <cstdio> #include <cstring>// strrchr #define MAX_PATH 256 int main(void) { char str[MAX_PATH]; char *ptr, c = '//'; strcpy(str, "C://TEST//sample.txt"); printf("%s/n",str); ptr = strrchr(str, c); if (ptr) *ptr='/0'; printf("%s/n",str); return 0; } /* output: C:/TEST/sample.txt C:/TEST */

[3] C的方法,不适用库函数的方法,通过循环自己查找。
#include <cstdio> #include <cstring>// strlen int main() { char str[]="C://TEST//sample.txt"; printf("%s/n",str); char *p=str+strlen(str)-1; for (; p>=str; --p) { if (*p=='//') { *p=0; break; } } printf("%s/n",str); return 0; } /* output: C:/TEST/sample.txt C:/TEST */
[4] 使用Windows的API的方法,PathRemoveFileSpec。
/* PathRemoveFileSpec Function Removes the trailing file name and backslash from a path, if they are present. need: #include "Shlwapi.h" Shlwapi.lib More: http://msdn.microsoft.com/en-us/library/bb773748%28VS.85%29.aspx */ #include <windows.h> #include <iostream> #include "Shlwapi.h" using namespace std; void main( void ) { // Path to include file spec. char buffer_1[ ] = "C://TEST//sample.txt"; char *lpStr1; lpStr1 = buffer_1; // Print the path with the file spec. cout << "The path with file spec is: " << lpStr1 << endl; // Call to "PathRemoveFileSpec". PathRemoveFileSpecA(lpStr1); // Print the path without the file spec. cout << "The path without file spec is: " << lpStr1 << endl; } /* output: The path with file spec is: C:/TEST/sample.txt The path without file spec is: C:/TEST */



你可能感兴趣的:(c,File,buffer,Path,include,output)