gpt4 book ai didi

c - 标记 O_CREAT 不创建文件

转载 作者:太空狗 更新时间:2023-10-29 15:25:26 24 4
gpt4 key购买 nike

我有一个程序试图创建一个文件并写入其中,但由于某种原因,当我使用 O_CREAT 标志时出现错误

No such file or directory

产生错误的代码部分:

(char *) datafile = malloc(30);
strcpy(datafile, "~/Desktop/notes");
fd = open(datafile, O_CREAT | O_WRONLY | O_APPEND, S_IRUSR | S_IWUSR); <----- here I get the error

最佳答案

"~/Desktop/notes"

那里没有名为~ 的目录。一些程序(最著名的是 bash 之类的 shell)将 ~ 扩展到当前用户的主目录,但是 open 不是 shell,也不会这样做。

如果你需要相对于主目录的路径,你可以这样做:

char* home = getenv("HOME");
if (home) {
strcpy(datafile, home);
strcat(datafile, "/Desktop/notes");
...
} else {
... report an error
}

关于c - 标记 O_CREAT 不创建文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54840228/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com