windows路径有两种方式,一种正斜杠,一种反斜杠都可以表示路径,该方法可以支持这两种表达方法
方法一:采用substr()进行分割
string path1 = "D:/datas/FusionTestData/datas/GF6_PMS_E111.2_N27.6_0719_L1A1119837939-PAN.tiff"string path2 = "D:\datas\FusionTestData\datas\GF6_PMS_E111.2_N27.6_0719_L1A1119837939-PAN.tiff"string::size_type iPos = (path1 .find_last_of('\\') + 1) == 0 ? path1 .find_last_of('/') + 1: path1 .find_last_of('\\') + 1 ;string ImgName = path1 .substr(iPos, path1 .length() - iPos);//获取带后缀的文件名string ImgPath = path1 .substr(0,iPos);//获取文件路径string ImgNameNoTag = ImgName.substr(0, ImgName.rfind("."));//获取不带后缀的文件名string ImgNameTag = ImgName.substr(ImgName.rfind("."),ImgName.length());//获取后缀名
方法2:使用_splitpath()函数分割路径,_makepath()函数组合路径
使用样例:
#include<iostream>int main(){string path1 = "D:/datas/FusionTestData/datas/GF6_PMS_E111.2_N27.6_0719_L1A1119837939-PAN.tiff";string path2 = "D:\datas\FusionTestData\datas\GF6_PMS_E111.2_N27.6_0719_L1A1119837939-PAN.tiff";string path3 = "D:\\datas\\FusionTestData\\datas\\GF6_PMS_E111.2_N27.6_0719_L1A1119837939-PAN.tiff";char orbitfilename[1024];char drive[_MAX_DRIVE];char dir[_MAX_DIR];char fname[_MAX_FNAME];char ext[_MAX_EXT];_splitpath(path1.c_str(), drive, dir, fname, ext);printf("drive:%s\n", drive);printf("dir:%s\n", dir);printf("fname:%s\n", fname);printf("ext:%s\n", ext);_makepath(orbitfilename, drive, dir, fname, "orbit");printf("orbitfilename:%s\n\n", orbitfilename);char orbitfilename2[1024];char drive2[_MAX_DRIVE];char dir2[_MAX_DIR];char fname2[_MAX_FNAME];char ext2[_MAX_EXT];_splitpath(path2.c_str(), drive2, dir2, fname2, ext2);printf("drive2:%s\n", drive2);printf("dir2:%s\n", dir2);printf("fname2:%s\n", fname2);printf("ext2:%s\n", ext2);_makepath(orbitfilename2, drive2, dir2, fname2, "test2");printf("orbitfilename2:%s\n\n", orbitfilename2);char orbitfilename3[1024];char drive3[_MAX_DRIVE];char dir3[_MAX_DIR];char fname3[_MAX_FNAME];char ext3[_MAX_EXT];_splitpath(path3.c_str(), drive3, dir3, fname3, ext3);printf("drive3:%s\n", drive3);printf("dir3:%s\n", dir3);printf("fname3:%s\n", fname3);printf("ext3:%s\n", ext3);_makepath(orbitfilename3, drive3, dir3, fname3, "test3");printf("orbitfilename3:%s\n\n", orbitfilename3);return 0;}
结果如下:
第二个路径是单反斜杠,有问题。改成双反斜杠也就OK了