CreateFile CREATE_NEW эквивалент в Linux

Я написал метод, который пытается создать файл. Однако я установил флаг CREATE_NEW, чтобы он мог создавать его только тогда, когда он не существует. Это выглядит так:

for (;;)
{
handle_ = CreateFileA(filePath.c_str(), 0, 0, NULL, CREATE_NEW, FILE_ATTRIBUTE_HIDDEN | FILE_FLAG_DELETE_ON_CLOSE, NULL);
if (handle_ != INVALID_HANDLE_VALUE)
break;

boost::this_thread::sleep(boost::posix_time::millisec(10));
}

Это работает как надо. Теперь я хочу перенести его в Linux и, конечно, функция CreateFile только для Windows. Так что я ищу что-то подобное, но на Linux. Я уже посмотрел на open (), но я не могу найти флаг, который работает как CREATE_NEW. Кто-нибудь знает решение для этого?

2

Решение

Посмотрите на open() страница руководства, сочетание O_CREAT а также O_EXCL это то, что вы ищете.

Пример:

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.
}
6

Другие решения

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.

Кроме того, creat () эквивалентно open () с флагами, равными O_CREAT | O_WRONLY | O_TRUNC.

Проверь это: http://linux.die.net/man/2/open

1

Это правильный и рабочий ответ:

#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.
}

Я разместил этот код для другого человека внутри комментария, потому что его вопрос закрыт … но этот код проверен мной на Ubuntu, и он работает точно так же, как CreateFileA и WriteFile.

Это создаст новый файл, как вы ищете.

0
По вопросам рекламы ammmcru@yandex.ru
Adblock
detector