简体   繁体   中英

When writing into a binary file, ofstream::write writes more bytes than it should

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.

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.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM