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
#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)
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)
| 归档时间: |
|
| 查看次数: |
26218 次 |
| 最近记录: |