Reputation: 33
Is there anyone could help me to check where I did wrong? Or explain why? I am a beginner and I tried my best to open the binary file. But it just runs out "file is open" "0". Nothing came out.
The objective: The Count3s program opens a binary file containing 32-bit integers (ints). Your program will count the number of occurrences of the value 3 in this file of numbers. Your objective is to learn about opening and accessing files and apply your knowledge of control structures. The name of the file containing data used by the program is "threesData.bin".
my code as below, please help me if you know it. Thank you 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 is open " << endl;
cout << count << endl; }
else
cout << "cannot open it" << endl;
return 0;
}
Upvotes: 3
Views: 10380
Reputation: 6407
First of all you should read from file opened in binary mode with
myfile.read (buffer,length);
where buffer
should be defined as
int data;
and used as
myfile.read (&data,sizeof(int));
The second important point is reading from file for more than one number - you need loop that is controled by condition that check stream. For example:
while (myfile.good() && !myfile.eof())
{
// read data
// then check and count value
}
And the last thing, you should close file, that was successfully oppened, after you finished reading:
myfile.open( "threesData.bin", ios::binary);
if (myfile)
{
while (myfile.good() && !myfile.eof())
{
// read data
// then check and count value
}
myfile.close();
// output results
}
And some additinal tips:
1) int
is not always 32-bit type, so consider using int32_t
from <cstdint>
; and if your data has more than 1 byte, may be byte order is important, but it was not mentioned in the task description
2) read
allows reading more than one data object per one call, but in that case you should read to array instead of one variable
3) read and try examples from references and other available resources like this.
Upvotes: 1