繁体   English   中英

creat()覆盖我的文件

[英]creat() overwrite my file

我用creat函数在Linux上写下了一个小的C代码。 我以相同的文件名和相同的mode使用了几次,每次它用新的时间和权限覆盖我的文件时都没有EEXIST错误。

 if (creat(name, mode) < 0)
{
    printf("something went wrong with create! %s\n", strerror(errno));
    exit(1);
}

问题是什么?

仅当O_CREAT | O_EXCL EEXIST返回O_CREAT | O_EXCL 在标志中使用O_CREAT | O_EXCL open 虽然creat(2)确实暗示O_CREAT ,但并不暗示O_EXCL ,仅暗示O_CREAT | O_WRONLY | O_TRUNC O_CREAT | O_WRONLY | O_TRUNC O_CREAT | O_WRONLY | O_TRUNC

您应该改用open

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 !
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM