How safe and correct is it to use a vector (vector unsigned char) instead of a character array (char []) when interacting with the file system using linux api (read,write)? Constructive criticism is needed. Are there any other alternatives?
I want to use this technique when writing a wrapper library (using classes).
Code example:
// This program was written to test the possibility of using a vector as a buffer
// for reading and writing to a file using linux api.
#include <iostream>
#include <vector>
#include <fcntl.h> // Linux API open
#include <unistd.h> // Linux API read,write,close
using namespace std;
int main() {
vector <unsigned char> buffer(10);
buffer[0] = '1';
buffer[1] = '2';
buffer[2] = '3';
buffer[3] = '4';
buffer[4] = '5';
buffer[5] = '5';
buffer[6] = '4';
buffer[7] = '3';
buffer[8] = '2';
buffer[9] = '1';
// Open new file for writing (create file)
int fd = 0;
const char *path = "./test.txt";
fd = (open(path, O_WRONLY | O_CREAT | O_TRUNC, S_IRWXU));
if (fd == -1) {
cout << "Can't open (create) file!!!" << endl;
return 0;
}
// Write to file from vector
write(fd, &buffer, buffer.size());
// Close file
close(fd);
// Open file for reading
fd = open(path, O_RDONLY);
vector <unsigned char> buffer1(10);
// Read from file to vector
read (fd,&buffer1,buffer1.size());
// close file
close(fd);
return 0;
}