我有一个程序试图创建一个文件并写入其中,但由于某种原因,当我使用 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/