我想知道与路径组件串联相关的问题,考虑到引入了过多的斜杠(如“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/