读取原始文件 C++
使用fstream class
读取数据时如何存储?一个例子可以澄清我的问题:
char * memBlock = NULL;
fileSize = file.tellg();
memBlock = **new** char[fileSize];
file.seekg(0, ios::beg);
file.read(memBlock, fileSize);
file.close();
if(memBlock)
return memBlock;
上下文是我正在读取以十六进制记录的原始图像,因此
- 表示像素的值是 00 或 ff (黑色或白色,1 或 0),
- 并按列排列和行。
读取内存中的文件时,memblock数组中的值是存储为ff和00还是通过ASCII或其他方式自动转换为1和0?
How is data stored when read in using fstream class
? An example will clarify my question:
char * memBlock = NULL;
fileSize = file.tellg();
memBlock = **new** char[fileSize];
file.seekg(0, ios::beg);
file.read(memBlock, fileSize);
file.close();
if(memBlock)
return memBlock;
The context is that I am reading a raw image that has been recorded in hex so that
- the values representing the pixels are either 00 or ff (black or white, 1 or 0)
- and are arranged in columns and rows.
When reading the file in memory, are the values in the memblock array
stored as ff and 00 or are they converted into 1 and 0 automatically by ASCII or something?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当数据存储为十六进制
并且您使用
file.read
读取它时,如代码所示,然后它就这样存储,这意味着它将
评估为 true。
编辑
您必须自己进行转换。一种方法是
When the data is stored as hex
and you read it using
file.read
as shown in your code,then it is stored as that, which means that
will evaluate to true.
EDIT
You have to make the conversion yourself. One way would be
要读取原始数据文件,首先必须以二进制模式打开文件,这不是
fstream
的默认模式。使用 file.open(文件名, std::ios::binary|std::ios::in) 。这样,读入内存缓冲区的内容将与文件内容完全相同。
因此,如果文件中有
00ff00ff
,那么您的内存中也会有00ff00ff
。不会有任何转换。如果你想将其转换为
0
和1
,假设使用00ff00ff
,你的意思是每个字节都是0x00, 0xff、0x00、0xff
,您可以进行以下转换:(如果00ff00ff
实际上是八个ASCII字符,请参阅esskar的答案)这将将缓冲区转换为二进制
0
和1
字节的序列。For reading raw data file, first you have to open your files in binary mode, which is not the default for
fstream
. Usefile.open(filename, std::ios::binary|std::ios::in)
.In this way, the content which is read into the memory buffer will be exactly the same as file content.
So if you have
00ff00ff
in the file, you will have00ff00ff
in your memory. There will be no conversion.If you want to convert it to
0
's and1
's, assuming with00ff00ff
, you mean each byte is0x00, 0xff, 0x00, 0xff
, you can do the following conversion : (if the00ff00ff
are in fact eight ASCII characters, see esskar's answer)This will convert the buffer into a serials of binary
0
and1
bytes.