gpt4 book ai didi

c - 如何检查路径是否通向 c 中的目录之外?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:32:43 25 4
gpt4 key购买 nike

我正在尝试检查路径是否通向当前目录的“上层”。示例:

我在 "./"

假设当前目录包含一个名为“folder”的文件夹

我想检查 cd "./folder/../../" 是否会将我带到“./”之外。在这种情况下,它会回答我 True。

这是为了将我的程序绑定(bind)到它的执行文件夹(我希望它执行 ls 但从不在外面)。

最佳答案

POSIX.1-2001 定义 realpath(3) :

#include <limits.h>
#include <stdlib.h>

char *realpath(const char *path, char *resolved_path);

realpath() expands all symbolic links and resolves references to /./, /../ and extra '/' characters in the null-terminated string named by path to produce a canonicalized absolute pathname. The resulting pathname is stored as a null-terminated string, up to a maximum of PATH_MAX bytes, in the buffer pointed to by resolved_path. The resulting path will have no symbolic link, /./ or /../ components.

您可以将规范化路径与当前目录进行比较,看看前者是否是后者的后代。

#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

bool is_inside(const char *parent, const char *child) {
char *abs_parent = realpath(parent, NULL);
if (!abs_parent) { perror(parent); exit(EXIT_FAILURE); }

char *abs_child = realpath(child, NULL);
if (!abs_child) { perror(child); exit(EXIT_FAILURE); }

size_t parent_len = strlen(abs_parent);
size_t child_len = strlen(abs_child);

bool result = strncmp(abs_parent, abs_child, parent_len) == 0 &&
(child_len == parent_len || abs_child[parent_len] == '/');

free(abs_parent);
free(abs_child);

return result;
}

int main(int argc, char **argv) {
if (argc != 3) {
fprintf(stderr, "usage: %s <parent> <child>\n", argv[0]);
return 1;
}

printf("%s\n", is_inside(argv[1], argv[2]) ? "yes" : "no");
return 0;
}

请注意,这仅在路径存在时才有效。

关于c - 如何检查路径是否通向 c 中的目录之外?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55613296/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com