问题描述
| 试题编号: | 201604-3 |
|---|---|
| 试题名称: | 路径解析 |
| 时间限制: | 1.0s |
| 内存限制: | 256.0MB |
| 问题描述: | 问题描述 在操作系统中,数据通常以文件的形式存储在文件系统中。文件系统一般采用层次化的组织形式,由目录(或者文件夹)和文件构成,形成一棵树的形状。文件有内容,用于存储数据。目录是容器,可包含文件或其他目录。同一个目录下的所有文件和目录的名字各不相同,不同目录下可以有名字相同的文件或目录。 为了指定文件系统中的某个文件,需要用路径来定位。在类 Unix 系统(Linux、Max OS X、FreeBSD等)中,路径由若干部分构成,每个部分是一个目录或者文件的名字,相邻两个部分之间用 / 符号分隔。 有一个特殊的目录被称为根目录,是整个文件系统形成的这棵树的根节点,用一个单独的 / 符号表示。在操作系统中,有当前目录的概念,表示用户目前正在工作的目录。根据出发点可以把路径分为两类: Ÿ 绝对路径:以 / 符号开头,表示从根目录开始构建的路径。 Ÿ 相对路径:不以 / 符号开头,表示从当前目录开始构建的路径。 例如,有一个文件系统的结构如下图所示。在这个文件系统中,有根目录 / 和其他普通目录 d1、d2、d3、d4,以及文件 f1、f2、f3、f1、f4。其中,两个 f1 是同名文件,但在不同的目录下。 |
\
#include<iostream>
#include<algorithm>
#include<vector>
#include<string>
using namespace std;
vector<string> split(string in, string sp)//分割字符串,解析参数
{
vector<string> rt;
while (in.find(sp) != -1)
{
string tem = in.substr(0, in.find(sp));
if (tem != "")
rt.push_back(tem);
in = in.substr(in.find(sp) + 1);
}
if (in != "")
rt.push_back(in);
return rt;
}
string generate_string(vector<string> in)
{
string rt = "";
for (int i = 0; i < in.size(); i++)
{
rt += ("/" + in[i]);
}
return rt;
}
int main()
{
int p;
cin >> p;
string current_path;
cin >> current_path;
vector < string> result;
for (int i = 0; i < p; i++)
{
string tem;
cin >> tem;
if (tem == "")
{
result.push_back(current_path);
continue;
}
if (tem == "/")
{
result.push_back(tem);
continue;
}
if (tem.find("./") == 0)//如果开头有相对路径,则加上当前路径
{
tem = current_path + tem.substr(2, tem.length() - 1);
}
if (tem.find("../") == 0)
{
tem = current_path + "/" + tem;
}
vector<string> this_path_parameter = split(tem, "/");
vector<string> new_path;
new_path.push_back("/");
for (int j = 0; j < this_path_parameter.size(); j++)
{
string a_file = this_path_parameter[j];
if (a_file == ".")
{
continue;
}
if (a_file == "..")//碰到需要处理上一级目录
{
if (new_path.size()>1)//大于等于2的时候才删除,因为/的上一级目录还是/所以不删除
new_path.erase(new_path.begin() + new_path.size() - 1);
}
else
{
new_path.push_back(a_file);
}
}
tem = generate_string(new_path);
if (tem[tem.length() - 1] == '/')//如果最后有斜杠直接删除它
{
tem.erase(tem.begin() + tem.length() - 1);
}
vector<string> tem_result = split(tem, "/");
tem = generate_string(tem_result);
if (tem == "")
tem = "/";
result.push_back(tem);
}
for (int i = 0; i < result.size(); i++)
{
cout << result[i] << endl;
}
//system("pause");
}
\