linux c++ 获取程序运行路径 不包括程序名称
时间: 2024-02-10 21:10:26 浏览: 31
在Linux C++中,可以通过获取程序运行时的完整路径,再通过处理字符串来获取程序运行路径,不包括程序名称。可以使用以下代码实现:
```c++
#include <iostream>
#include <unistd.h>
#include <limits.h>
int main()
{
char buffer[PATH_MAX];
ssize_t len = readlink("/proc/self/exe", buffer, sizeof(buffer)-1);
if (len != -1)
{
buffer[len] = '\0';
std::string path(buffer);
std::string::size_type pos = path.find_last_of('/');
if (pos != std::string::npos)
{
path = path.substr(0, pos+1);
std::cout << "The program is running in the directory: " << path << std::endl;
}
}
return 0;
}
```
该程序通过读取 `/proc/self/exe` 符号链接获取程序的完整路径,并通过查找最后一个 `/` 字符来获取程序运行路径,不包括程序名称。
相关问题
C++ 获取当前路径 不能用getcwd
如果你的操作系统是 Windows,你可以使用 GetModuleFileName 函数获取当前程序的完整路径,然后从中提取出当前路径。
示例代码如下:
```cpp
#include <windows.h>
#include <iostream>
int main() {
char buffer[MAX_PATH];
GetModuleFileName(NULL, buffer, MAX_PATH);
std::string::size_type pos = std::string(buffer).find_last_of("\\/");
std::cout << std::string(buffer).substr(0, pos) << std::endl;
return 0;
}
```
如果你的操作系统是 Linux 或者 macOS,你可以使用 proc 文件系统获取当前进程的完整路径,然后从中提取出当前路径。
示例代码如下:
```cpp
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <limits.h>
#include <iostream>
int main() {
char buffer[PATH_MAX];
ssize_t len = ::readlink("/proc/self/exe", buffer, sizeof(buffer));
if (len != -1) {
buffer[len] = '\0';
std::string::size_type pos = std::string(buffer).find_last_of("\\/");
std::cout << std::string(buffer).substr(0, pos) << std::endl;
}
return 0;
}
```
Linux下获取指定文件路径的创建时间,用c++编码实现,
您好,对于 Linux 下获取指定文件路径的创建时间的需求,可以使用 C 语言提供的系统调用和文件相关的函数来实现。
具体步骤如下:
1、使用 stat() 函数获取指定文件路径的相关信息,其中包括创建时间、修改时间、文件大小等。
2、通过 st_ctime 成员获取文件的创建时间,st_ctime 存储的是文件状态最后一次改变的时间,包括修改、属性改变等。
3、将 st_ctime 成员中存储的创建时间转换为可读日期格式,例如使用 ctime() 函数将时间戳转换为字符串。
以下是一个简单的示例代码:
```
#include <stdio.h>
#include <sys/stat.h>
#include <time.h>
int main()
{
char *path = "/path/to/file"; // 指定文件路径
struct stat file_stat;
// 获取指定文件路径的文件信息
if (stat(path, &file_stat) < 0) {
fprintf(stderr, "Failed to get file info.\n");
return -1;
}
printf("File create time: %s\n", ctime(&file_stat.st_ctime));
return 0;
}
```
需要注意的是,ctime() 函数在转换时间戳时会自动添加换行符,可以通过输出格式进行修改。此外,如果文件不存在或读取权限不足等问题都会导致获取文件信息失败,请在程序中进行相应的判断和处理。