简体   繁体   English

C ++从文件读取/写入N个精确字节(甚至是'00'字节)

[英]C++ read / write N exact bytes from file (even '00' bytes)

My task is read file contents and place them into vector array of std::strings, then output from vector to another file. 我的任务是读取文件内容并将它们放入std :: strings的向量数组中,然后从vector输出到另一个文件。

I managed to solve it for file containing only normal text, but failed with, lets say .bmp Here is .bmp file header: 我设法解决它只包含普通文本的文件,但失败了,让我们说.bmp这里是.bmp文件头:

BM)(     6   (   —  к        Р((

hex shows these are NULL bytes, not whitespaces 十六进制显示这些是NULL字节,而不是空格

42 3d 06 29 28 00 00 00 00 00 36 00 00 00 ...

As a result , executing the following code 结果,执行以下代码

char *buffer = new char [50];

ifstream ifs( "file.bmp" , std::ifstream::binary );
ifs >> std::noskipws;

ifs.read( buffer, 50 );

std::string abc(buffer); //output it to other file next

i end up with buffer and abc strings equal to "BM)(6(—кР(( ..." with all nullbytes skipped. ifs.read() was great until now. So whats the most comfortable way to read/write N exact bytes from a file ? 我最终得到缓冲区和abc字符串等于“BM”(6(-кР((...“跳过所有nullbytes.ifs.read()直到现在都很棒。所以最简单的读/写方式是什么?文件中的确切字节数?

(I did a search but had difficulties with results) (我做了搜索,但结果有困难)

That was lame, but somebody might google this someday so i ll write an answer. 这是蹩脚的,但有一天可能有人会谷歌,所以我会写一个答案。

If while debugging you would hover mouse over buffer after calling ifs.read() you would see "BM)(6(—кР(( ..." , but the null bytes are actually there. But (in MSVS) you couldnt see actual bytes buffer has unless you redefine buffer as 如果在调试时你会在调用ifs.read()后将鼠标悬停在缓冲区上,你会看到“BM”(6(-кР((...“,但实际上是空字节。但是(在MSVS中)你看不到实际的字节缓冲区有,除非你重新定义缓冲区为

char buffer[50];

Next, when making std::string out of buffer, doing 接下来,当使用缓冲区生成std :: string时,这样做

string abc(buffer); // would not copy null bytes to std string,

So do this instead: 所以这样做:

string abc(buffer, 50); //copies all bytes.

Now i have the real file contents in the string and if i output abc to other file i will have same data. 现在我有字符串中的真实文件内容,如果我输出abc到其他文件我会有相同的数据。

PS when checking results use hex editor to see real bytes, dont trust Notepad. PS检查结果时使用十六进制编辑器查看实际字节,不要信任记事本。

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

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