5.分离字符串路径的方法
处理文件的程序可能要分析文件名。这种算法要进行字符串处理。文件可以
由路径名指定,路径名包括由分隔符"/"分割的名称集。最后一个"/"前的名称序列
称为路径。最后一个名称是文件名,还可能包括扩展名。
路径名 /class/programs/testfile.cpp
路径 /class/programs/
文件名 testfile.cpp
扩展名 cpp
为了分析文件名,我们从键盘读入完整的路径名,并输出路径和文件名。
如果文件名具有扩展名"cpp",则在创建可执行文件名时,将用"exe"替代扩展名"cpp".
下面是程序结构的轮廓,以及如何使用字符串函数的说明:
1.输入文件名,使用函数find_last_of()在字符串中搜索最后一个出现的"/"。这个字符
确定了路径的结尾和文件名的开始。
2。路径是由最后一个"/"前所有字符串组成的子串。文件名是最后一个"/"后的
所有字符。使用最后一个"/"的位置和substr()提取出路径和文件名。
3.扩展名是文件名中最好一个"."后的字符串。调用find_last_of()搜索最后一个匹配,
则复制文件名,删除当前扩展名,并添加新的扩展名"exe"。 输出产生的可执行文件名。
// 文件prg1_3.cpp
// 此程序提示用户输入文件的路径
// 它使用string类操作来识别并输出
// 路径名和文件名。如果文件名有
// 扩展名"cpp",则创建并输出
// 可执行文件的名称,其扩展名为"exe",替换
// 扩展名"cpp"
// WJ.cpp : 定义控制台应用程序的入口点。
//
#i nclude "stdafx.h"
#i nclude<iostream>
#i nclude<string>
using namespace std;
int main()
{
string pathname, path, filename,executableFile;
// ‘/’和 '.'的位置
int backslashIndex, dotIndex;
cout << "Enter the path name: ";
cin >> pathname;
// 识别最后一个'/'的位置。注意:由于
// 转义码如'/n'以/起始,
// c++ 使用'//'表示 /
backslashIndex = pathname.find_last_of('//');
//路径名是最后一个'/'之前的字符
path = pathname.substr(0,backslashIndex);
cout << "path: " << path << endl;
// 路径名尾部是文件名
filename = pathname.substr(backslashIndex+1,-1);
cout << "Filename: " << filename << endl;
// 查看文件名是否有'.cpp'扩展名。
// 首先找到最后一个'.'的位置。 如果
// 没有'.',则dotIndex为-1
dotIndex = filename.find_last_of('.');
//测试是否有'.',其余的字符是否为"cpp"
if (dotIndex != -1 && filename.substr(dotIndex+1) == "cpp")
{
// 删除"cpp",并加上"exe"设置可执行字符串
executableFile = filename;
executableFile.erase(dotIndex+1,3);
executableFile+="exe";
cout << "Executable: " << executableFile << endl;
}
return 0;
}
输出结果:
第1次允许结果:
Enter the path name: /class/programs/testfile
path: /class/programs
Filename: testfile
第2次允许结果:
Enter the path name: programs/strings/filedemp.cpp
path: programs/strings
Filename: filedemo.cpp
Executable: filedemo.exe
第3次允许结果:
Enter the path name: /program.cpp
path:
Filename: program.cpp
Executable: program.exe
char szFileName [MAX_PATH];
::GetModuleFileName(g_hinstDll, szFileName, MAX_PATH);