如何从C++中的路径中提取文件名和扩展名

Oct*_*ian 65 c++ string file-io

我有一个.log以这种语法存储在a 中的文件列表:

c:\foto\foto2003\shadow.gif
D:\etc\mom.jpg
Run Code Online (Sandbox Code Playgroud)

我想从这些文件中提取名称和扩展名.你能给出一个简单方法的例子吗?

Nic*_*kin 156

要提取没有扩展名的文件名,请使用boost :: filesystem :: path :: stem而不是ugly std :: string :: find_last_of(".")

boost::filesystem::path p("c:/dir/dir/file.ext");
std::cout << "filename and extension : " << p.filename() << std::endl; // file.ext
std::cout << "filename only          : " << p.stem() << std::endl;     // file
Run Code Online (Sandbox Code Playgroud)

  • 实际上,p.filename()的类型为path,并且在隐式转换时将被引号括起,因此您将获得:filename和extension:"file.ext"您可能需要p.filename().string(). (10认同)
  • 使用C++ 14/C++ 17,您可以使用`std :: experimental :: filesystem` resp`std :: filesystem`.请看下面的Yuchen Zhong的帖子. (4认同)
  • 提问者想要一个简单的方法。仅针对此功能向项目添加提升并不是一个简单的方法。std::filesystem 是简单的方法。 (2认同)
  • C++17 将 &lt;filesystem&gt; 包含到标准库中。使用新的编译器...或导入 boost。 (2认同)

Kos*_*Kos 19

如果你想要一种安全的方式(即在平台之间移植而不在路径上进行假设),我建议使用boost::filesystem.

它看起来像这样:

boost::filesystem::path my_path( filename );
Run Code Online (Sandbox Code Playgroud)

然后,您可以从此路径中提取各种数据.这是路径对象的文档.


顺便说一句:还记得为了使用路径之类的

c:\foto\foto2003\shadow.gif
Run Code Online (Sandbox Code Playgroud)

你需要转义\字符串文字:

const char* filename = "c:\\foto\\foto2003\\shadow.gif";
Run Code Online (Sandbox Code Playgroud)

或者/改为使用:

const char* filename = "c:/foto/foto2003/shadow.gif";
Run Code Online (Sandbox Code Playgroud)

这仅适用于在""引号中指定文字字符串,从文件加载路径时问题不存在.

  • +1肯定是要走的路.主站点上的示例提供了一种搜索目录的方法:使用path.extension()方法搜索日志(请参阅http://www.boost.org/doc/libs/1_36_0/libs/filesystem/doc/index热媒) (2认同)

Yuc*_*ong 18

对于C++ 17:

#include <filesystem>

std::filesystem::path p("c:/dir/dir/file.ext");
std::cout << "filename and extension: " << p.filename() << std::endl; // "file.ext"
std::cout << "filename only: " << p.stem() << std::endl;              // "file"
Run Code Online (Sandbox Code Playgroud)

有关文件系统的参考:http://en.cppreference.com/w/cpp/filesystem


正如@RoiDanto所建议的那样,对于输出格式,std::out可以用引号括输出,例如:

filename and extension: "file.ext"
Run Code Online (Sandbox Code Playgroud)

您可以转换std::filesystem::pathstd::string通过p.filename().string(),如果这就是你所需要的,例如:

filename and extension: file.ext
Run Code Online (Sandbox Code Playgroud)


Syl*_*sne 16

你必须从文件中读取你的文件名std::string.您可以使用字符串提取运算符std::ostream.在a中有文件名后std::string,可以使用该std::string::find_last_of方法查找最后一个分隔符.

像这样的东西:

std::ifstream input("file.log");
while (input)
{
    std::string path;
    input >> path;

    size_t sep = path.find_last_of("\\/");
    if (sep != std::string::npos)
        path = path.substr(sep + 1, path.size() - sep - 1);

    size_t dot = path.find_last_of(".");
    if (dot != std::string::npos)
    {
        std::string name = path.substr(0, dot);
        std::string ext  = path.substr(dot, path.size() - dot);
    }
    else
    {
        std::string name = path;
        std::string ext  = "";
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 不想成为聪明的驴子,但它应该是path.substr而不是path.substring,对吗? (2认同)