libbz2的问题

时间:2015-05-24 19:05:01

标签: c compression

我无法让libbz2工作。在10 000个字符之后,它以流结束终止,尽管输入文件包含几千兆字节。我只是无法弄清楚出了什么问题。谢谢你的任何评论。

这是我的代码:

string read_bz2_file(const string& filename) {
string result;
FILE* f;
BZFILE* b;
const int BUFSIZE = 1000;
char buf[BUFSIZE];
int bzerror;

f = fopen(filename.c_str(), "r");

if (!f) {
    /* handle error */
    cerr << "cannot read file " << filename << endl;
    return "";
}


b = BZ2_bzReadOpen(&bzerror, f, 0, 0, NULL, 0);
if (bzerror != BZ_OK) {
    BZ2_bzReadClose(&bzerror, b);
    cerr << "cannot read file " << filename << endl;
    return "";
    /* handle error */
}

bzerror = BZ_OK;
while (bzerror == BZ_OK /* arbitrary other conditions */) {
    BZ2_bzRead(&bzerror, b, buf, BUFSIZE /* size of buf */);
    cout << "bzerror: " << bzerror << endl;
    if (bzerror == BZ_OK) {
            /* do something with buf[0 .. nBuf-1] */
        result.append(buf);
    }
}
if (bzerror != BZ_STREAM_END) {
    BZ2_bzReadClose(&bzerror, b);
    cerr << "error while reading file " << filename << endl;
    return "";
    /* handle error */
} else {
    result.append(buf);
    BZ2_bzReadClose(&bzerror, b);
    return result;
}
return result;
}

1 个答案:

答案 0 :(得分:1)

您可以尝试以二进制模式打开文件,在fopen模式中添加“b”:

f = fopen(filename.c_str(), "rb");