如何用C语言获取服务器的物理路径?
- 行业动态
- 2025-01-22
- 4828
在C语言中,要获取服务器的物理路径,通常需要使用系统特定的API或函数。在Windows上,你可以使用
GetModuleFileName
函数来获取当前可执行文件的路径,然后解析出目录部分作为服务器的物理路径。在Linux上,则可以使用
readlink
函数读取
/proc/self/exe
符号链接来获取可执行文件的路径。,,以下是一个简化的示例代码,展示如何在Windows和Linux上分别获取服务器物理路径:,,“
c,#include,#include,,#ifdef _WIN32,#include,#else,#include,#endif,,int main() {, char path[1024];,,#ifdef _WIN32, DWORD result = GetModuleFileName(NULL, path, sizeof(path));, if (result == 0 || result == sizeof(path)) {, fprintf(stderr, "Failed to get module file name,");, return 1;, }, // Remove the file name part to get the directory, char *lastSlash = strrchr(path, '\');, if (lastSlash) {, *lastSlash = '