ifstream读取二进制文件内容

0 views
Skip to first unread message

bruc...@gmail.com

unread,
Sep 16, 2005, 3:13:28 AM9/16/05
to 星星爱CPP
// 方法1
#include <fstream>
#include <vector>
#include <iostream>
using namespace std;

int main(int argc, char* argv[])
{
// 打开文件
ifstream f( "a.bin", ios_base::in|ios_base::binary );
if( !f ) return 1;

// 获取文件长度
streampos cp = f.tellg();
f.seekg( 0, ios_base::end );
streampos len = f.tellg();
f.seekg( 0, ios_base::beg );

// 读取内容
vector<char> buf( len );
f.read( &buf[0], len );

return 0;
}


// 方法2
#include <fstream>
#include <iterator>
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;

int main(int argc, char* argv[])
{
// 打开文件
ifstream f( "a.bin", ios_base::in|ios_base::binary );
if( !f ) return 1;

// 定义存放容器
vector<char> buf;

// 读取内容
copy( istreambuf_iterator<char>(f), istreambuf_iterator<char>(),
back_inserter(buf) );

return 0;
}

---

Reply all
Reply to author
Forward
Message has been deleted
0 new messages