溫馨提示×

linux copendir如何判斷目錄是否存在

小樊
106
2024-12-28 22:04:08
欄目: 智能運維

在Linux中,您可以使用copendir()函數來創建一個新的目錄,同時檢查給定的父目錄是否存在

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>

int copendir(const char *dir, const char *newdir) {
    struct stat st;

    // 檢查父目錄是否存在
    if (stat(dir, &st) == -1 || !S_ISDIR(st.st_mode)) {
        perror("Error checking if parent directory exists");
        return -1;
    }

    // 創建新目錄
    if (copydir(dir, newdir) == -1) {
        perror("Error creating new directory");
        return -1;
    }

    return 0;
}

int main() {
    const char *parent_dir = "/path/to/parent";
    const char *new_dir = "/path/to/new";

    if (copendir(parent_dir, new_dir) == 0) {
        printf("New directory created successfully.\n");
    } else {
        printf("Failed to create new directory.\n");
    }

    return 0;
}

在這個示例中,我們首先使用stat()函數檢查給定的父目錄是否存在。如果存在并且是一個目錄,我們繼續使用copydir()函數創建新的子目錄。如果父目錄不存在或者不是一個目錄,我們返回-1并輸出錯誤信息。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女