简体   繁体   English

在 C++ 中存储和检索字符向量(向量<char> ) 来自文件的所有零值(即 '\0' 或字符串终止符)</char>

[英]In C++ storing and retrieving of character vector (vector<char>) of all zero value (i.e. '\0' or string terminator) from file

Using fstream I have created a file to store a fixed length sequence of zero value (0) ie '\0' ASCII code available in a character vector (vector).使用fstream我创建了一个文件来存储一个固定长度的零值 (0) 序列,即字符向量 (vector) 中可用的 '\0' ASCII 码。

fstream Fpt;

Fpt.open("Data.bin",ios::out|ios::binary);

std::vector<char> V;

char c=0;

for(int i=0;i<10;i++)V.push_back(c);

Fpt.write((char *)&V,10);

Fpt.close();

Fpt.open("Data.bin",ios::in | ios::out|ios::binary);

V.clear();

Fpt.read((char *)&V, 10);

for(auto v: V) printf("(%c,%d,%X)",v,v,v);

But the output is looking like (▌,-35,FFFFFFDD) (▌,-35,FFFFFFDD)...但是 output 看起来像 (▌,-35,FFFFFFDD) (▌,-35,FFFFFFDD)...

You write the vector object itself, not the data wrapped by the vector (which is located on the heap).您编写向量 object 本身,而不是向量包装的数据(位于堆上)。

You need to get a pointer to the data itself and write that:您需要获取指向数据本身的指针并写入:

Fpt.write(V.data(), V.size());

Similarly when you read the data, you need to read it into the wrapped data:同样,在读取数据时,需要将其读入包装好的数据中:

V = std::vector<char>(10);  // Reset the vector, remembering to set its size
Fpt.read(V.data(), V.size());

This statement is not correct:这种说法是不正确的:

Fpt.write((char *)&V,10);

You are getting the address of the vector object V which is stored on the stack.您正在获取存储在堆栈中的向量 object V的地址。 What you want is the address of the underlying buffer (stored on the heap) that V points at and so you need to use the data member function.您想要的是V指向的底层缓冲区(存储在堆上)的地址,因此您需要使用data成员 function。

So instead do this:所以改为这样做:

Fpt.write( V.data(), 10 );

Or this:或这个:

Fpt.write( &V[0], 10 );

Important Note重要的提示

What you do here is a bad idea:你在这里做的是一个坏主意:

char c=0;

for ( int i = 0; i < 10; i++ ) V.push_back(c);

This will cause the vector to repeatedly reallocate its buffer once the size reaches capacity.一旦大小达到容量,这将导致向量重复重新分配其缓冲区。 This is bad in terms of performance.这在性能方面很糟糕。
Instead, write it like:相反,把它写成:

std::vector<char> V(10);

Now V will be initialized with 10 \0 characters.现在V将被初始化为 10 个\0字符。 No need to use a loop to fill the container.无需使用循环来填充容器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM