CreateFile CREATE_NEW equivalent on linux

后端 未结 3 1713
清歌不尽
清歌不尽 2021-01-14 05:40

I wrote a method which tries to create a file. However I set the flag CREATE_NEW so it can only create it when it doesnt exist. It looks like this:

for (;;)
         


        
3条回答
  •  误落风尘
    2021-01-14 06:38

    fd = open("path/to/file", O_CREAT | O_EXCL | O_RDWR | O_CLOEXEC);
    
    O_CREAT: Creates file if it does not exist. If the file exists, this flag has no effect.
    O_EXCL: If O_CREAT and O_EXCL are set, open() will fail if the file exists.
    O_RDWR: Open for reading and writing.
    

    Also, creat() is equivalent to open() with flags equal to O_CREAT|O_WRONLY|O_TRUNC.

    Check this: http://linux.die.net/man/2/open

提交回复
热议问题