如何从路径中获取文件名的词干?

lua*_*uac 3 c++ regex filenames scanf

我想从const char*文件路径中提取一个const char*文件名.我尝试使用正则表达式但失败了:

const char* currentLoadedFile = "D:\files\file.lua";
char fileName[256];
if (sscanf(currentLoadedFile, "%*[^\\]\\%[^.].lua", fileName)) {
return (const char*)fileName; // WILL RETURN "D:\files\file!!
}
Run Code Online (Sandbox Code Playgroud)

问题是将返回"D:\ files\file"而不是想要的"文件"(注意:没有".lua")

Bat*_*hyX 15

只是用boost::filesystem.

#include <boost/filesystem.hpp>

std::string filename_noext;
filename_noext = boost::filesystem::path("D:\\files\\file.lua").stem().string().
const char* result_as_const_char = filename_noext.c_str();
Run Code Online (Sandbox Code Playgroud)

或者,如果你想自己介绍bug:

// have fun defining that to the separator of the target OS.
#define PLATFORM_DIRECTORY_SEPARATOR '\\'

// the following code is guaranteed to have bugs.
std::string input = "D:\\files\\file.lua";
std::string::size_type filename_begin = input.find_last_of(PLATFORM_DIRECTORY_SEPERATOR);
if (filename_begin == std::string::npos)
    filename_begin = 0;
else
    filename_begin++;
std::string::size_type filename_length = input.find_last_of('.');
if (filename_length != std::string::npos)
    filename_length = filename_length - filename_begin;

std::string result = input.substr(filename_begin, filename_length);

const char* bugy_result_as_const_char = result.c_str();
Run Code Online (Sandbox Code Playgroud)

  • 为什么?正则表达式不是标准C++的一部分,因此您必须使用非标准函数.重写现有的众所周知的好免费代码浪费了每个人的时间.良好的编程正在充分利用资源 (4认同)
  • @luac如果你不能使用Boost,我可以假设这是一个功课问题吗?:P (2认同)

mar*_*ing 15

那么使用std :: string呢?例如

  std::string path("d:\\dir\\subdir\\file.ext");
  std::string filename;

  size_t pos = path.find_last_of("\\");
  if(pos != std::string::npos)
    filename.assign(path.begin() + pos + 1, path.end());
  else
    filename = path;
Run Code Online (Sandbox Code Playgroud)

  • 这将产生"file.ext",而OP想要返回"file".这也不适用于UNIX. (2认同)