从路径获取文件名 [英] Get a file name from a path

查看:137
本文介绍了从路径获取文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从路径获取文件名的最简单的方法是什么?

What is the simplest way to get the file name that from a path?

string filename = "C:\\MyDirectory\\MyFile.bat"

在这个例子中,我应该得到MyFile。无延伸。

In this example, I should get "MyFile". without extension.

推荐答案

_ splitpath 应该做你需要的。你当然可以手动执行,但 _splitpath 也可以处理所有特殊情况。

_splitpath should do what you need. You could of course do it manually but _splitpath handles all special cases as well.

编辑:

正如BillHoag所提到的,建议使用 _splitpath 更安全的版本 _ splitpath_s (如果有的话)。

As BillHoag mentioned it is recommended to use the more safe version of _splitpath called _splitpath_s when available.

可以做这样的事情

std::vector<std::string> splitpath(
  const std::string& str
  , const std::set<char> delimiters)
{
  std::vector<std::string> result;

  char const* pch = str.c_str();
  char const* start = pch;
  for(; *pch; ++pch)
  {
    if (delimiters.find(*pch) != delimiters.end())
    {
      if (start != pch)
      {
        std::string str(start, pch);
        result.push_back(str);
      }
      else
      {
        result.push_back("");
      }
      start = pch + 1;
    }
  }
  result.push_back(start);

  return result;
}

...
std::set<char> delims{'\\'};

std::vector<std::string> path = splitpath("C:\\MyDirectory\\MyFile.bat", delims);
cout << path.back() << endl;

这篇关于从路径获取文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆