Posted on 2010-10-12 11:30
柯枫 阅读(4433)
评论(0) 编辑 收藏 引用 所属分类:
C/C++
1 #include <iostream>
2 #include <fstream>
3
4 int main()
5 {
6 int length;
7 char *buffer;
8
9 std::fstream rfile;
10 rfile.open("test.txt",std::fstream::in|std::fstream::binary);
11 if(!rfile)
12 {
13 std::cerr<<"Open test.txt failed!"<<std::endl;
14 return -1;
15 }
16
17 //get length of file:
18 rfile.seekg(0,std::ios::end);
19 length = rfile.tellg();
20 rfile.seekg(0,std::ios::beg);
21 std::cout<<"length:"<<length<<std::endl;
22
23 //allocate memory:
24 buffer = new char[length];
25
26 //read data as a block:
27 rfile.read(buffer,length);
28 rfile.close();
29
30 //write to outfile
31 std::fstream wfile("new.txt",std::fstream::out|std::fstream::binary);
32 wfile.write(buffer,length);
33
34 //delete buffer
35 delete[] buffer;
36
37 //close rfile wfile
38 rfile.close();
39 wfile.close();
40
41 return 0;
42 }
43