在C中的文件系统中创建一个目录

标签 c directory

我正在用 C 语言做一个项目,我被困在一件事上,我需要检查目录“/var/log/PROJECT”是否存在,如果不存在,我的程序必须创建它,应用程序将始终在 super 用户上运行,这就是我正在做的:

    struct stat st = {0};

  if (stat("/var/log/project/PROJECT", &st) == -1) {
    printf("im creating the folder\n");
    mode_t process_mask = umask(0);
    int result_code = mkdir("/var/log/project/PROJECT", 0777);
    umask(process_mask);

}else{
    printf("exist\n");

}

抱歉要求“做作业”,但我真的陷入困境......

最佳答案

好吧,我要带着我的怀疑逃跑。如果问题是您尝试创建的目录的父目录不存在,则解决方案是在它之前创建父目录。值得庆幸的是,用递归来做到这一点并不是非常困难。试试这个:

#include <errno.h>
#include <libgen.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>

int create_directory_with_parents(char const *pathname, mode_t modus) {
  struct stat st;

  if(stat(pathname, &st) == -1) {
    // If the directory does not yet exist:
    //
    // Make sure the parent directory is there. dirname() gives us the name of
    // the parent directory, then we call this very function recursively because
    // we are, after all, in a function that makes sure directories exist.
    char *path_cpy = strdup(pathname);
    char *dir      = dirname(path_cpy);
    int   err      = create_directory_with_parents(dir, modus);
    free(path_cpy);

    // If we were able to make sure the parent directory exists,
    // make the directory we really want.
    if(err == 0) {
      mode_t process_mask = umask(0);
      int err = mkdir(pathname, modus);
      umask(process_mask);
    }

    // err is 0 if everything went well.
    return err;
  } else if(!S_ISDIR(st.st_mode)) {
    // If the "directory" exists but is not a directory, complain.
    errno = ENOTDIR;
    return -1;
  }

  // If the directory exists and is a directory, there's nothing to do and
  // nothing to complain about.
  return 0;
}

int main(void) {
  if(0 != create_directory_with_parents("/var/log/project/PROJECT", 0777)) {
    perror("Could not create directory or parent of directory: ");
  }
}

当发现第一个父目录存在时,递归结束;最晚是 /

此实现的一个限制是所有父目录都将具有与叶目录相同的访问权限,这可能是也可能不是您想要的。如果这不是您想要的,则必须将递归调用中的 modus 参数更改为 create_directory_with_parents。如何为可能必须创建的多层父目录传递多个 modus 参数是一个设计问题,具体取决于您的具体需求,因此我无法给出一般性答案。

关于在C中的文件系统中创建一个目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27770934/

相关文章:

更改堆栈空间

c - 正确使用 volatile sig_atomic_t

c - 在多线程中将多个小片段写入 c 中的临时文件的正确方法是什么?

python - 是否可以监控 Windows 驱动器上的每个文件创建?

C - 使用递归函数将文件夹和子文件夹中的所有 wav 文件路径放入字符串数组中

windows - 在目录/子目录中生成文件夹 list.txt 文件,并在批处理文件中使用 dir & ren 命令将 list.txt 重命名为文件夹/子文件夹名称

c - Windows 上的 LibVNC 编译错误 : Unresolved External Symbol

c - 守护进程如何在启动时自动运行

C: 如何列出目录中文件和子目录的数量

drupal - 如何递归地保护/sites 文件夹?