C++ 读取二进制文件时使用变量的问题
我正在编写一些串口代码,需要将文件内容(二进制)读取到变量中。 从“二进制文件”的示例开始, 我尝试打开一个.jpg文件:C++ 读取二进制文件时使用变量的问题,c++,binaryfiles,C++,Binaryfiles,我正在编写一些串口代码,需要将文件内容(二进制)读取到变量中。 从“二进制文件”的示例开始, 我尝试打开一个.jpg文件: #include <iostream> #include <fstream> using namespace std; ifstream::pos_type size; char * memblock; int main () { ifstream file ("example.jpg", ios::in|ios::binary|ios::a
#include <iostream>
#include <fstream>
using namespace std;
ifstream::pos_type size;
char * memblock;
int main () {
ifstream file ("example.jpg", ios::in|ios::binary|ios::ate);
if (file.is_open())
{
size = file.tellg();
memblock = new char [size];
file.seekg (0, ios::beg);
file.read (memblock, size);
file.close();
cout << memblock << endl;
delete[] memblock;
}
else cout << "Unable to open file";
return 0;
}
它创建了一个新的.jpg文件
所以我的问题是为什么memblock变量似乎只包含前4个字符。二进制数据中可能有一个0
cout
是一个文本流,因此将memblock
视为一个字符串。如果达到空字符,则认为字符串已完成
有关输出二进制数据的帮助信息,请参见以下内容:
Hmmm。快速浏览一下您引用的页面,就会发现作者没有 对C++中的IO有很多了解。避免它,因为它说的很多是 错 对于其余部分:
.jpg
不是文本格式,不能简单地输出
到cout
。当您使用
ofstream fileOut ("writtenFile.jpg",ios::out|ios::binary);
fileOut.write(memblock,size);
fileOut.close();
template <typename InputIterator>
void
process(
InputIterator begin,
InputIterator end,
std::ostream& output = std::cout )
{
IOSave saveAndRestore( output ) ;
output.setf( std::ios::hex, std::ios::basefield ) ;
output.setf( std::ios::uppercase ) ;
output.fill( '0' ) ;
static int const lineLength( 16 ) ;
while ( begin != end ) {
int inLineCount = 0;
unsigned char buffer[ lineLength ] ;
while ( inLineCount != lineLength && begin != end ) {
buffer[inLineCount] = *begin;
++ begin;
++ inLineCount;
}
for ( int i = 0 ; i < lineLength ; ++ i ) {
static char const *const
separTbl [] =
{
" ", " ", " ", " ",
" ", " ", " ", " ",
" ", " ", " ", " ",
" ", " ", " ", " ",
} ;
output << separTbl[ i ] ;
if ( i < inLineCount ) {
output << std::setw( 2 )
<< static_cast< unsigned int >(buffer[ i ] & 0xFF) ) ;
} else {
output << " " ;
}
}
output << " |" ;
for ( int i = 0 ; i != inLineCount ; ++ i ) {
output << (i < lengthRead && isprint( buffer[ i ] )
? static_cast< char >( buffer[ i ] )
: ' ') ;
}
output << '|' << std::endl ;
}
}