【问题标题】:Create a directory in filesystem in C在 C 文件系统中创建一个目录
【发布时间】:2015-01-04 22:12:25
【问题描述】:

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

    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");

}

很抱歉要求“做我的作业”,但我真的卡住了......

【问题讨论】:

  • 使用函数system()执行系统命令!
  • 要运行超级用户,您只需以超级用户身份运行可执行文件,它将获得所有必需的权限!
  • /var/log/project/ 是否存在,rwx 是 root 用户吗?如果您尝试创建的目录的父目录尚不存在,mkdir 将失败。
  • mkdir -p /var/log/project/ 将完成这项工作,即使父母不在!
  • 我不认为在其中生成一个 shell 和另一个进程来创建一个目录是解决这个问题的明智之举。

标签: c directory


【解决方案1】:

好吧,我要带着我的怀疑逃跑了。如果问题是您尝试创建的目录的父目录不存在,解决方法是在它之前创建父目录。谢天谢地,这对递归来说并不难。试试这个:

#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。如何为可能必须创建的几层父目录传递几个模式参数是一个设计问题,这取决于您的需求,因此我无法给出一般性的答案。

【讨论】:

    【解决方案2】:

    为什么不直接执行mkdir 命令,而忽略目录已经存在时会产生的错误?这样你就不用玩stat了。

    您是否需要将文件权限设为777?如果没有,您也可以删除umask 位。

    【讨论】:

      猜你喜欢
      • 2015-01-31
      • 1970-01-01
      • 1970-01-01
      • 2013-02-06
      • 1970-01-01
      • 2012-08-22
      • 1970-01-01
      • 2020-06-13
      • 1970-01-01
      相关资源
      最近更新 更多