binaryfiles - how to open and read a binary file in C++ by a given bin file? -
is there me check did wrong? or explain why? beginner , tried best open binary file. runs out "file open" "0". nothing came out.
the objective: count3s program opens binary file containing 32-bit integers (ints). program count number of occurrences of value 3 in file of numbers. objective learn opening , accessing files , apply knowledge of control structures. name of file containing data used program "threesdata.bin".
my code below, please me if know it. thank in advance!
#include <iostream> #include <fstream> using namespace std; int main() { int count=0 ; ifstream myfile; myfile.open( "threesdata.bin", ios::in | ios :: binary | ios::ate); if (myfile) { cout << "file open " << endl; cout << count << endl; } else cout << "cannot open it" << endl; return 0; }
first of should read file opened in binary mode
myfile.read (buffer,length);
where buffer
should defined as
int data;
and used as
myfile.read (&data,sizeof(int));
the second important point reading file more 1 number - need loop controled condition check stream. example:
while (myfile.good() && !myfile.eof()) { // read data // check , count value }
and last thing, should close file, oppened, after finished reading:
myfile.open( "threesdata.bin", ios::binary); if (myfile) { while (myfile.good() && !myfile.eof()) { // read data // check , count value } myfile.close(); // output results }
and additinal tips:
1) int
not 32-bit type, consider using int32_t
<cstdint>
; , if data has more 1 byte, may byte order important, not mentioned in task description
2) read
allows reading more 1 data object per 1 call, in case should read array instead of 1 variable
3) read , try examples references , other available resources this.
Comments
Post a Comment