C++/File/Binary File
Версия от 17:21, 25 мая 2010; (обсуждение)
Содержание
Binary Files
<source lang="cpp">
- include <iostream>
using namespace std;
- include <fstream>
int main () {
long start,end; ifstream myfile ("test.txt", ios::in|ios::binary); start = myfile.tellg(); myfile.seekg (0, ios::end); end = myfile.tellg(); myfile.close(); cout << "size of " << "test.txt"; cout << " is " << (end-start) << " bytes.\n"; return 0;
}
</source>
binary input and output with integers
<source lang="cpp">
- include <fstream>
- include <iostream>
using namespace std; const int MAX = 100; int buff[MAX];
int main(){
for(int j=0; j<MAX; j++) buff[j] = j; ofstream os("edata.dat", ios::binary); os.write( reinterpret_cast<char*>(buff), MAX*sizeof(int) ); os.close(); for(int j=0; j<MAX; j++) buff[j] = 0; ifstream is("edata.dat", ios::binary); is.read( reinterpret_cast<char*>(buff), MAX*sizeof(int) ); for(int j=0; j<MAX; j++){ if( buff[j] != j ){ cerr << "Data is incorrect\n"; return 1; } } cout << "Data is correct\n"; return 0;
}
</source>
reading a complete binary file
<source lang="cpp">
- include <iostream>
- include <fstream>
using namespace std; ifstream::pos_type size; char * memblock; int main () {
ifstream file ("example.txt", 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 << "the complete file content is in memory"; delete[] memblock; }else cout << "Unable to open file"; return 0;
}
</source>
seeks particular person in file
<source lang="cpp">
- include <fstream>
#include <iostream> using namespace std; class person { protected: char name[80]; int age; public: void getData(){ cout << "\n Enter name: "; cin >> name; cout << " Enter age: "; cin >> age; } void showData(void){ cout << "\n Name: " << name; cout << "\n Age: " << age; } }; int main(){ person pers; ifstream infile; infile.open("GROUP.DAT", ios::in | ios::binary); infile.seekg(0, ios::end); int endposition = infile.tellg(); int n = endposition / sizeof(person); cout << "\nThere are " << n << " persons in file"; cout << "\nEnter person number: "; cin >> n; int position = (n-1) * sizeof(person); infile.seekg(position); infile.read( reinterpret_cast<char*>(&pers), sizeof(pers) ); pers.showData(); cout << endl; return 0; } </source>
Write numbers to a binary file and read them back
<source lang="cpp">
- include <iostream>
- include <fstream>
using namespace std; int main(void){
float fnum[4] = {11.22, -33.44, 55.66, 77.88}; int i; ofstream out("numbers.asc", ios::out | ios::binary); if(!out){ cout << "Cannot open file."; exit (1); } out.write((char *) &fnum, sizeof(fnum)); out.close(); for (i=0; i<4; i++) fnum[i] = 0.0; ifstream in("numbers.asc", ios::in | ios::binary); if(!in) { cout << "Cannot open file."; exit (1); } in.read((char *) &fnum, sizeof(fnum)); cout << in.gcount() << " bytes read." << endl; for (i=0; i<4; i++) cout << fnum[i] << " "; in.close();
}
</source>