Linux API 和 C++ STD 向量

Linux API and C++ STD vector

在使用linux api(阅读,写)?需要建设性的批评。还有其他选择吗?

我想在编写包装器库时使用这种技术(使用类)。

代码示例:

// 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;
}

关于您的疑惑和问题

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)?

std::vector<uint8_t>std::array<uint8_t,const_size>std::string 与需要连续的 API 函数一起使用是完全安全的(在 std::string 的情况下为 null 终止) unsigned char[]char[].

数组

上面提到的所有这些 classes 都提供了一个 data() 成员,允许直接访问底层数据。

Are there any other alternatives?

是的,还有其他方法可以更手动地管理这些指针,例如std::unique_ptrstd::shared_ptr,但通常您不需要它们。

I want to use this technique when writing a wrapper library (using classes).

这是创建此类 API 包装器 classes 的常用、灵活且可靠的技术。


关于您的示例代码

// Write to file from vector
write(fd, &buffer, buffer.size());

// Read from file to vector
read (fd,&buffer1,buffer1.size());

是错误的,因为&buffer(1)没有指向std::vectorclass.[=34=管理的底层数据的地址]

您需要使用 std::vector<T>::data() 函数来访问指向基础数据的指针:

// Write to file from vector
write(fd, buffer.data(), buffer.size());

// Read from file to vector
read (fd,buffer1.data(),buffer1.size());

Constructive criticism is needed. Are there any other alternatives?

在您的特定情况下,您似乎主要希望从基础文件写入和读取文本。在这种情况下,我更愿意使用 std::string 而不是 std::vector<unsigned char>.

这样可以更轻松地编写

std::string buffer = "123455432";

用于数据初始化。