std::string 获取文件路径,文件名称
时间: 2024-04-08 19:26:38 浏览: 449
要获取文件路径和文件名称,可以使用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类型。
相关问题
std::string = argv[1]; std::string img_path = argv[2];
这段代码是在 C++ 程序中获取命令行参数,将第一个参数赋值给变量 name,将第二个参数赋值给变量 img_path,两个变量的类型都是 std::string。
通常情况下,程序需要从命令行获取用户输入的参数,例如执行一个图片处理程序时,需要指定图片文件的路径作为参数。这时候就可以使用 argc 和 argv 参数来获取用户输入的参数。其中,argc 是一个整数,表示命令行参数的个数;argv 是一个字符串指针数组,其中每个元素指向一个命令行参数。第一个参数 argv[0] 是程序的名称,而后面的参数依次是用户输入的参数。
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`类来处理这个路径,最后输出当前进程的名称。
阅读全文
相关推荐














