How can I create directory tree in C?

家住魔仙堡 提交于 2020-06-28 09:16:16

问题


I want an easy way to create multiple directories in C.

For example I want to create directory in:

/a/b/c

but if the directories are not there I want them to be created automagically. How can I do this ?


回答1:


Here is a small C program to create the directory tree a/b/c in the current directory:

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

int create_dir(char *name)
{
    int rc;

    rc = mkdir(name, S_IRWXU);
    if (rc != 0 && errno != EEXIST) 
    {
        perror("mkdir");
        exit(1);
    }
    if (rc != 0 && errno == EEXIST)
        printf("%s already exists.\n", name);

    return 0;
}

int main(int argc, char **argv)
{

    create_dir("a");
    create_dir("a/b");
    create_dir("a/b/c");

    exit(0);
}


来源:https://stackoverflow.com/questions/62189792/how-can-i-create-directory-tree-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!