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)
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)
这仅适用于在""引号中指定文字字符串,从文件加载路径时问题不存在.
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::path到std::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)