从文件路径c ++获取目录 [英] get directory from file path c++

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

问题描述

获取文件所在目录的最简单的方法是什么?我使用它来找到工作目录。

What is the simplest way to get the directory that a file is in? I'm using this to find the working directory.

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

在这个例子中,我应该得到C:\ MyDirectory。

In this example, I should get "C:\MyDirectory".

推荐答案

初始化不正确,因为您需要转义反斜杠:

The initialisation is incorrect as you need to escape the backslashes:

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

如果存在则解压缩目录:

To extract the directory if present:

string directory;
const size_t last_slash_idx = filename.rfind('\\');
if (std::string::npos != last_slash_idx)
{
    directory = filename.substr(0, last_slash_idx);
}

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

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