简体   繁体   English

在 C 中创建一个新目录

[英]Creating a new directory in C

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 语言做到这一点?

Look at stat for 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 stat and man 2 mkdir commands.您可以使用man 2 statman 2 mkdir命令查看这些函数的手册。

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

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.因为这是一个非常常见的问题,这里是创建多级目录而不是调用 fopen 的代码。 I'm using a gnu extension to print the error message with printf.我正在使用 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);
}
  1. As Paul R. said you can use mkdir without stat to only use one systemcall.正如 Paul R. 所说,您可以在没有stat 的情况下使用mkdir来仅使用一个系统调用。

  2. mkdir has the errno -> EEXIST if you need the information that the directory exists.如果您需要目录存在的信息, mkdir有 errno -> EEXIST。

int mkdir (const char *filename, mode_t mode)

#include <sys/types.h>
#include <errno.h>
#include <string.h>

if (mkdir("/some/directory", S_IRWXU | S_IRWXG | S_IRWXO) == -1) {
    printf("Error: %s\n", strerror(errno));
}

For best practice it is recommended to use an integer-alias for mode .为获得最佳实践,建议对mode使用整数别名。 The argument mode specifies the file permissions for the new directory file.参数mode指定新目录文件的文件权限。

Read + Write + Execute: S_IRWXU (User), S_IRWXG (Group), S_IRWXO (Others)读 + 写 + 执行:S_IRWXU(用户)、S_IRWXG(组)、S_IRWXO(其他)

Source: https://www.gnu.org/software/libc/manual/html_node/Permission-Bits.html来源: https : //www.gnu.org/software/libc/manual/html_node/Permission-Bits.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM