CreateFile CREATE_NEW equivalent on linux

后端 未结 3 1682
清歌不尽
清歌不尽 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:19

    Take a look at the open() manpage, the combination of O_CREAT and O_EXCL is what you are looking for.

    Example:

    mode_t perms = S_IRWXU; // Pick appropriate permissions for the new file.
    int fd = open("file", O_CREAT|O_EXCL, perms);
    if (fd >= 0) {
        // File successfully created.
    } else {
        // Error occurred. Examine errno to find the reason.
    }
    
    0 讨论(0)
  • 2021-01-14 06:35

    This is the correct and working answer:

    #include <fcntl2.h> // open
    #include <unistd.h> // pwrite
    
    //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.
    
    int file = open("myfile.txt", O_CREAT | O_EXCL | O_RDWR | O_CLOEXEC);
    
    if (file >= 0) {
        // File successfully created.
        ssize_t rc = pwrite(file, "your data", sizeof("myfile.txt"), 0);
    } else {
        // Error occurred. Examine errno to find the reason.
    }
    

    I posted this code for another person, inside a comment because his question is closed... but this code is tested by me on Ubuntu and it's working exactly as CreateFileA and WriteFile.

    It will create a new file as you are seeking.

    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题