溫馨提示×

C++ getcwd如何處理符號鏈接

c++
小樊
102
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
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女