当目录不存在时使用 `open` 打开相关文件

Relative File Opening with `open` When Directory Doesn't Exist

我正在遵循 黑客:剥削的艺术 中的示例代码,运行 在 运行 以下内容时遇到问题。

datafile = (char *) ec_malloc(20);
strcpy(datafile, "/tmp/notes");

fd = open(datafile, O_WRONLY|O_CREAT|O_APPEND, S_IRUSR|S_IWUSR);
if (fd == -1)
    fatal("in main() while opening file");

错误信息是:

[!!] Fatal Error in main() while opening file: No such file or directory

"No such file or directory" 之前的位是使用自定义 fatal() 函数创建的。

请注意,/tmp/notes 不存在于程序的位置,但 O_CREAT 标志应该说明了这一点(或者我认为如此)。我试过将 strcpy 段切换为 ".\tmp\notes" 但结果是一样的。如何创建调用程序的目录中尚不存在的目录?

我在 Windows 10 上使用 MinGW,并且正在使用 gcc.

进行编译

你说 /tmp/notes 不存在 "in the program's location." 这意味着你是 运行 目录 FOO 中的程序并期望它创建一个类似于 FOO/tmp/notes 的文件。但是你实际要求的是/tmp/notes,这是一个绝对路径。您可能希望 tmp/notes 没有前导斜杠,但那也是一个目录加上一个文件,而 open() 不会创建目录。因此,要么只使用 notes 作为在当前目录中打开的文件,要么使用 tmp/notes 并首先调用 mkdir("tmp").