std::string 获取文件路径,文件名称
时间: 2024-04-08 21:26:38 浏览: 35
要获取文件路径和文件名称,可以使用std::filesystem库中的函数。首先,你需要包含<filesystem>头文件,并使用命名空间std::filesystem。
下面是获取文件路径和文件名称的示例代码:
```cpp
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
int main() {
fs::path filePath = "C:/path/to/file.txt";
// 获取文件路径
fs::path directoryPath = filePath.parent_path();
std::cout << "文件路径: " << directoryPath << std::endl;
// 获取文件名称
std::string fileName = filePath.filename().string();
std::cout << "文件名称: " << fileName << std::endl;
return 0;
}
```
在上面的示例中,我们使用了fs::path类型来表示文件路径。通过调用parent_path()函数可以获取文件所在的目录路径,而调用filename()函数可以获取文件的名称。注意,filename()函数返回的是一个fs::path对象,我们可以通过调用string()函数将其转换为std::string类型。
相关问题
c++17怎么用std::filesystem::path获取linux当前进程名
你可以使用`/proc`文件系统来获取当前进程的名称,然后使用`std::filesystem::path`类来处理这个路径。具体代码如下:
```c++
#include <iostream>
#include <fstream>
#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <filesystem>
int main() {
char path[100];
pid_t pid = getpid();
sprintf(path, "/proc/%d/cmdline", pid);
int fd = open(path, O_RDONLY);
char buf[1024];
ssize_t n = read(fd, buf, sizeof(buf));
close(fd);
std::string cmdline(buf, n);
std::filesystem::path p(cmdline);
std::cout << "Current process name: " << p.filename() << std::endl;
return 0;
}
```
这段代码首先获取当前进程的PID,然后使用`sprintf`函数构造`/proc/PID/cmdline`路径,从而获取当前进程的命令行参数。接着使用`std::filesystem::path`类来处理这个路径,最后输出当前进程的名称。
c++ 获取当前文件夹下某个匹配名称的文件路径
你可以使用C++的标准库中的`<filesystem>`头文件来获取当前文件夹下某个匹配名称的文件路径。具体实现方法如下:
```c++
#include <filesystem>
#include <iostream>
int main()
{
std::filesystem::path path = "./"; // 指定当前目录
std::string filename = "example.txt"; // 要匹配的文件名称
for (const auto& file : std::filesystem::directory_iterator(path))
{
if (file.is_regular_file() && file.path().filename().string() == filename)
{
std::cout << "File found: " << file.path() << std::endl;
}
}
return 0;
}
```
在上述代码中,我们使用了`std::filesystem::directory_iterator`来遍历当前目录下的所有文件,然后判断是否是普通文件,并且文件名是否与我们要匹配的文件名相同。如果是,则输出该文件的路径。