Here is my code snippet:
void
DirectIO::writeFileUnix(const std::string &file_path,
unsigned long long int index,
size_t size,
std::string &bytes_data) {
WRITE_COUNT++;
const int file_descriptor = open(file_path.c_str(),
O_WRONLY | O_DIRECT | O_SYNC | O_CREAT, S_IRUSR | S_IWUSR);
if (file_descriptor == -1 || size % SECTOR_SIZE != 0) {
throw std::exception();
}
char *buffer = &bytes_data[0];
ssize_t number_of_bytes_written = pwrite(file_descriptor, buffer, size, index * size);
if (number_of_bytes_written == -1 || number_of_bytes_written < size) {
throw std::exception();
}
close(file_descriptor);
}
The function seems correct logically. But number_of_bytes_written
is always -1. The file may get created if not exists. I don't understand why it isn't working.
Update 1
Okay, so I got the problem. char* buffer
is limited by null character. Hence, the line char *buffer = &bytes_data[0];
will point to a only a small part of string bytes_data
.
When I came to know this, I updated that part of my code to
void *buffer = bytes_data.data();
ssize_t number_of_bytes_written = pwrite(file_descriptor, buffer, size, index * size);
if (number_of_bytes_written == -1 || number_of_bytes_written < size) {
throw std::exception();
}
And data()
function of std::string
doesn't care about null characters according to its C++ reference page as well as this SO post
But still, it isn't working out.
If anyone wants to try out the code, I am posting here my sample data to try on.
bytes_data - "\000\000\000\000\005\000\000\000\000\000\000\000\000\000\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\000....\000" (octal representation as supported by clion)
index = 0
size = 4096 (length of bytes_data)
file_path = "abc.binary"
Update 2
I tried writing a string will no null character and still it throws an error. Hence, the problem isn't will null character. This seems some memory alignment issue as the disk alignment is already taken care of (I might be wrong because of my limited knowledge in C++).