[英]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;
}
在使用 linux api(讀、寫)與文件系統交互時,使用向量(向量無符號字符)而不是字符數組(字符 [])有多安全和正確?
將std::vector<uint8_t>
、 std::array<uint8_t,const_size>
、 std::string
與 API 函數一起使用是完全安全的std::array<uint8_t,const_size>
API 函數期望一個連續的(在std::string
情況下為空終止)數組的任一unsigned char[]
或char[]
。
上面提到的所有這些類都提供了一個data()
成員,允許直接訪問底層數據。
還有其他選擇嗎?
是的,還有其他替代方法可以更手動地管理這些指針,例如std::unique_ptr
或std::shared_ptr
,但通常您不需要它們。
我想在編寫包裝庫(使用類)時使用這種技術。
這是創建此類 API 包裝器類的常用、靈活和健壯的技術。
// Write to file from vector
write(fd, &buffer, buffer.size());
和
// Read from file to vector
read (fd,&buffer1,buffer1.size());
是錯誤的,因為&buffer
( 1
) 不指向由std::vector
類管理的底層數據的地址。
您需要使用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());
需要建設性的批評。 還有其他選擇嗎?
在您的特定情況下,您似乎希望主要從底層文件中寫入和讀取文本。 在這種情況下,我更喜歡使用std::string
而不是std::vector<unsigned char>
。
這使得編寫類似的東西更容易
std::string buffer = "123455432";
用於數據初始化。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.