Reputation: 129
I first read data from a binary matrix file and write to a new file, the I use another program to read them into memory.
write part
#define BIT_NUM 8
using namespace std;
int main(int argc, char **argv) {
if (argc >= 2) {
char* filename = argv[1];
ifstream fin(filename);
ofstream fout("../../hashcode.dat", ios_base::trunc | ios_base::out | ios_base::binary);
char c;
bitset<BIT_NUM> temp;
int index = 0;
int count = 0;
while (fin.get(c)) {
if (c != '\n' && c != ',') {
temp.set(BIT_NUM - index - 1, c - '0');
index++;
}
if (index == BIT_NUM) {
unsigned char byte = static_cast<unsigned char>(temp.to_ulong());
fout.put(byte);
count++;
index = 0;
}
}
cout << count << "\n";
fin.close();
fout.close();
}
return 0;
}
output:14610144
read part
#define BIT_NUM 256
#define BYTE_NUM 32
using namespace std;
int main(int argc, char **argv) {
ifstream fin("../../hashcode.dat", ios_base::binary);
char buff[1];
int count = 0;
while(fin) {
fin.read(buff, 1);
count++;
/**/
}
cout << count << "\n";
return 0;
}
output:14610145
I try to diff the results and find that the extra byte is in the tail and is the same as a final byte. I wonder why the I/O process would make an extra byte like this. When I view the output file hashcode.dat's property, its size is exactly 14610144 bytes.
Upvotes: 0
Views: 920
Reputation: 6016
For the read part:
#define BIT_NUM 256
#define BYTE_NUM 32
using namespace std;
int main(int argc, char **argv) {
ifstream fin("../../hashcode.dat", ios_base::binary);
char buff[1];
int count = 0;
while(fin.read(buff, 1)) {
count++;
/**/
}
cout << count << "\n";
return 0;
}
Upvotes: 1
Reputation: 308186
It's the read loop in the second part. Suppose the file was empty; the first time through fin
would still be true
because you've opened the file successfully but haven't tried to read from it yet, and you'd increment count
to 1
when it should stay at 0
.
You need to rearrange the loop so it only increments the count after a successful read.
Upvotes: 1