Linux 在 C 中创建一个新目录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7430248/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 06:13:13  来源:igfitidea点击:

Creating a new directory in C

clinuxdirectory

提问by Jeegar Patel

I want to write a program that checks for the existence of a directory; if that directory does not exist then it creates the directory and a log file inside of it, but if the directory already exists, then it just creates a new log file in that folder.

我想编写一个程序来检查目录是否存在;如果该目录不存在,则它会在其中创建目录和日志文件,但如果该目录已存在,则它只会在该文件夹中创建一个新的日志文件。

How would I do this in C with Linux?

我将如何在 Linux 中用 C 语言做到这一点?

采纳答案by Arnaud Le Blanc

Look at statfor checking if the directory exists,

查看stat目录是否存在,

And mkdir, to create a directory.

并且mkdir,创建一个目录。

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

struct stat st = {0};

if (stat("/some/directory", &st) == -1) {
    mkdir("/some/directory", 0700);
}

You can see the manual of these functions with the man 2 statand man 2 mkdircommands.

您可以使用man 2 statman 2 mkdir命令查看这些功能的手册。

回答by Paul R

You can use mkdir:

您可以使用 mkdir:

$ man 2 mkdir

$ man 2 mkdir

#include <sys/stat.h>
#include <sys/types.h>

int result = mkdir("/home/me/test.txt", 0777);

回答by Jens Harms

I want to write a program that (...) creates the directory and a (...) file inside of it

我想编写一个程序,该程序 (...) 在其中创建目录和一个 (...) 文件

because this is a very common question, here is the code to create multiple levels of directories and than call fopen. I'm using a gnu extension to print the error message with printf.

因为这是一个非常常见的问题,这里是创建多级目录而不是调用 fopen 的代码。我正在使用 gnu 扩展来打印带有 printf 的错误消息。

void rek_mkdir(char *path) {
    char *sep = strrchr(path, '/');
    if(sep != NULL) {
        *sep = 0;
        rek_mkdir(path);
        *sep = '/';
    }
    if(mkdir(path, 0777) && errno != EEXIST)
        printf("error while trying to create '%s'\n%m\n", path); 
}

FILE *fopen_mkdir(char *path, char *mode) {
    char *sep = strrchr(path, '/');
    if(sep) { 
        char *path0 = strdup(path);
        path0[ sep - path ] = 0;
        rek_mkdir(path0);
        free(path0);
    }
    return fopen(path,mode);
}