我在linux上用creat
函数写下了一个小的C代码。我使用相同的文件名和相同的mode
几次使用它,并且每次用新的时间和权限覆盖我的文件而没有EEXIST
错误。
if (creat(name, mode) < 0)
{
printf("something went wrong with create! %s\n", strerror(errno));
exit(1);
}
有什么问题?
答案 0 :(得分:3)
EEXIST
的标记中使用O_CREAT | O_EXCL
时,才会返回 open
。虽然creat(2)
确实意味着O_CREAT
,但它并不意味着O_EXCL
,只意味着O_CREAT | O_WRONLY | O_TRUNC
。
您应该使用open
。
答案 1 :(得分:3)
creat()函数与:
相同open(path, O_CREAT | O_TRUNC | O_WRONLY, mode);
您需要在文件末尾写入标记O_APPEND
因此,您应该使用open()
read()
write()
修改强>
例如:
#include <fcntl.h>
#include <unistd.h>
int is_file_exist (char *filename)
{
struct stat buffer;
return (stat (filename, &buffer) == 0);
}
void open_read_write() {
int fd;
if (!is_file_exist("./file"))
return ;
// open a file descriptor, if not, create
fd = open("./file", O_RDWR | O_APPEND);
// thanks to O_APPEND, write() writes at the end of the file
write(fd, "hello world\n", 12);
// close the file descriptor
close(fd); // important !
}