C(Linux和Windows)中的跨平台目录pathvalidation

我有一个C函数接受目录path作为一个string。 该函数在给定path中创build一个目录。

int create_directory(const char *path) { // given path may be absolute or relative // step 1:-need to validate the given path(cross platform for both Linux and windows) // what are the criteria for path validation? // step 2:- check permission about user accessibility ,means can not create directory, if path is like /usr/bin or /root).but in root login then we create. So what are the criteria for validation? // step 3:-if directory, subdirectory already exist at the path, then return? // step 4:-if not exists then create directory ; } 

基本上我在步骤1和步骤2有问题。我无法确定pathvalidation的确切标准是什么。

检查提供给您的路径的有效性的最好方法是尝试使用它。 操作系统会给你一个错误代码( errnoGetLastError()或其他),你可以使用它来确定为什么它是不可能的。

我会让底层操作系统执行验证。

创建目录,然后检查错误代码。

Linux使用“/”来分隔给定路径中的目录,而Windows使用“\”加上几乎所有的以C:\\开头的窗口路径或( D:\\不重要的是D:\\所以你可以使用strchr()来寻找这些符号,或者你可以使用perror() ,这很容易(你必须包含<errno.h>