我想编写一个程序来检查目录是否存在;如果该目录不存在,则会在其中创建目录和日志文件,但如果该目录已存在,则只会在该文件夹中创建一个新的日志文件。
如何在 C 语言和 Linux 中做到这一点?
最佳答案
看stat
用于检查目录是否存在,
还有 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);
}
您可以使用 man 2 stat
和 man 2 mkdir
命令查看这些函数的手册。
关于在 C 中创建一个新目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7430248/