c - 处理过多的路径分隔符

标签 c linux unix path posix

我想知道与路径组件串联相关的问题,考虑到引入了过多的斜杠(如“foo//bar”)导致路径最终无效的特殊情况通过不正确的串联。

但是我随后注意到 Linux 上有一个奇怪的行为。请参阅以下内容:

#include <stdio.h>

int main(void) {
    char buf[4];
    FILE *f = fopen("/tmp/bar", "w");
    fwrite("bar", 1, 3, f);
    fclose(f);
    f = fopen("/tmp////////bar", "r");
    if (f) {
        fread(buf, 1, 3, f);
        buf[3] = '\0';
        printf("%s\n", buf);
        fclose(f);
    }
    return 0;
}

上面的程序实际上打印了 bar,这意味着 "/tmp////////bar" 被隐式简化为 "/tmp/栏”。现在,这是标准行为吗?我可以依赖它,还是应该显式检查路径组件以确保它们格式良好?

最佳答案

这是标准(POSIX,2004):

3.266 Pathname

A character string that is used to identify a file. In the context of IEEE Std 1003.1-2001, a pathname consists of, at most, {PATH_MAX} bytes, including the terminating null byte. It has an optional beginning slash, followed by zero or more filenames separated by slashes. A pathname may optionally contain one or more trailing slashes. Multiple successive slashes are considered to be the same as one slash.

2013 年修订版具有类似的措辞,但定义了精确的路径名 //(两个斜杠,没有其他内容)实现。

关于c - 处理过多的路径分隔符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22202852/

相关文章:

Android API 中断

linux - 当同一驱动程序的多个实例同时运行时,内核如何处理对 proc 文件的读取操作

关于 pthread_attr_t 定义的困惑

ruby-on-rails - 通过 unix shell 在控制台上执行多个命令

linux - cut 或 awk 命令打印第一行的第一个字段

c - 简单的C程序来说明乱序执行?

c - 如何在内核中动态分配数组?

objective-c - C 数组和 Objective-C 中的代码

c++ - 在 C 中,当管道输入到另一个程序时,它无法打开

java - 如何将 Mat 转换为位图?(在 linux 上运行,而不是 android)