温馨提示×

C++ getcwd如何处理符号链接

c++
小樊
104
2024-11-27 15:16:14
栏目: 编程语言

getcwd() 函数用于获取当前工作目录的绝对路径

#include <iostream> #include <unistd.h> #include <limits.h> #include <sys/stat.h> int main() { char cwd[PATH_MAX]; if (getcwd(cwd, sizeof(cwd)) != nullptr) { std::cout << "Current working directory: " << cwd << std::endl; } else { perror("getcwd() error"); return 1; } // 处理符号链接 struct stat st; if (stat(cwd, &st) == 0) { if (S_ISLNK(st.st_mode)) { std::cout << "The current working directory is a symbolic link." << std::endl; // 获取符号链接指向的实际路径 char real_cwd[PATH_MAX]; if (readlink(cwd, real_cwd, sizeof(real_cwd)) != nullptr) { std::cout << "Real working directory: " << real_cwd << std::endl; } else { perror("readlink() error"); return 1; } } } else { perror("stat() error"); return 1; } return 0; } 

这个程序首先使用 getcwd() 获取当前工作目录的绝对路径,然后使用 stat() 检查路径是否为符号链接。如果是符号链接,程序将使用 readlink() 获取符号链接指向的实际路径,并将其输出到控制台。

0