不要使用 basic_ifstream,因为它需要专业化。
使用静态缓冲区:
linux ~ $ cat test_read.cpp
#include <fstream>
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main( void )
{
string filename("file");
size_t bytesAvailable = 128;
ifstream inf( filename.c_str() );
if( inf )
{
unsigned char mDataBuffer[ bytesAvailable ];
inf.read( (char*)( &mDataBuffer[0] ), bytesAvailable ) ;
size_t counted = inf.gcount();
cout << counted << endl;
}
return 0;
}
linux ~ $ g++ test_read.cpp
linux ~ $ echo "123456" > file
linux ~ $ ./a.out
7
使用向量:
linux ~ $ cat test_read.cpp
#include <fstream>
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main( void )
{
string filename("file");
size_t bytesAvailable = 128;
size_t toRead = 128;
ifstream inf( filename.c_str() );
if( inf )
{
vector<unsigned char> mDataBuffer;
mDataBuffer.resize( bytesAvailable ) ;
inf.read( (char*)( &mDataBuffer[0]), toRead ) ;
size_t counted = inf.gcount();
cout << counted << " size=" << mDataBuffer.size() << endl;
mDataBuffer.resize( counted ) ;
cout << counted << " size=" << mDataBuffer.size() << endl;
}
return 0;
}
linux ~ $ g++ test_read.cpp -Wall -o test_read
linux ~ $ ./test_read
7 size=128
7 size=7
在第一次调用中使用保留而不是调整大小:
linux ~ $ cat test_read.cpp
#include <fstream>
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main( void )
{
string filename("file");
size_t bytesAvailable = 128;
size_t toRead = 128;
ifstream inf( filename.c_str() );
if( inf )
{
vector<unsigned char> mDataBuffer;
mDataBuffer.reserve( bytesAvailable ) ;
inf.read( (char*)( &mDataBuffer[0]), toRead ) ;
size_t counted = inf.gcount();
cout << counted << " size=" << mDataBuffer.size() << endl;
mDataBuffer.resize( counted ) ;
cout << counted << " size=" << mDataBuffer.size() << endl;
}
return 0;
}
linux ~ $ g++ test_read.cpp -Wall -o test_read
linux ~ $ ./test_read
7 size=0
7 size=7
如您所见,如果不调用 .resize(counted),向量的大小将是错误的。请记住这一点。使用强制转换很常见,请参阅cppReference