I am extracting data from the bzip2 stream in application C. Since pieces of data come out of the decompressor, they can be written to stdout :
fwrite(buffer, 1, length, stdout);
This works great. I get all the data when it is sent to stdout .
Instead of writing to stdout , I would like to process the output from this statement inside one row: a line that ends with a newline \n .
Do I write the output of the decompressor stream to another buffer, one character at a time, until I click on a new line, and then call the processing function in the line? Is it slow and a smarter approach? Thank you for your advice.
EDIT
Thanks for your suggestions. I ended up creating a pair of buffers that store the remainder (the "stub" at the end of the output buffer) at the beginning of the short string buffer every time I pass the value of the output buffer.
I process the character of the output buffer by the character and process the data in one line of a line at a time. The remainder without a new line is allocated and assigned and copied to the next stream line buffer. It appears that realloc less expensive than the repetitive malloc-free statements.
Here is the code I came up with:
char bzBuf[BZBUFMAXLEN]; BZFILE *bzFp; int bzError, bzNBuf; char bzLineBuf[BZLINEBUFMAXLEN]; char *bzBufRemainder = NULL; int bzBufPosition, bzLineBufPosition; bzFp = BZ2_bzReadOpen(&bzError, *fp, 0, 0, NULL, 0); if (bzError != BZ_OK) { BZ2_bzReadClose(&bzError, bzFp); fprintf(stderr, "\n\t[gchr2] - Error: Bzip2 data could not be retrieved\n\n"); return -1; } bzError = BZ_OK; bzLineBufPosition = 0; while (bzError == BZ_OK) { bzNBuf = BZ2_bzRead(&bzError, bzFp, bzBuf, sizeof(bzBuf)); if (bzError == BZ_OK || bzError == BZ_STREAM_END) { if (bzBufRemainder != NULL) { strncpy(bzLineBuf, bzBufRemainder, strlen(bzBufRemainder)); bzLineBufPosition = strlen(bzBufRemainder); } for (bzBufPosition = 0; bzBufPosition < bzNBuf; bzBufPosition++) { bzLineBuf[bzLineBufPosition++] = bzBuf[bzBufPosition]; if (bzBuf[bzBufPosition] == '\n') { bzLineBuf[bzLineBufPosition] = '\0'; fprintf(stdout, "%s", bzLineBuf); bzLineBufPosition = 0; } else if (bzBufPosition == (bzNBuf - 1)) { bzLineBuf[bzLineBufPosition] = '\0'; if (bzBufRemainder != NULL) bzBufRemainder = (char *)realloc(bzBufRemainder, bzLineBufPosition); else bzBufRemainder = (char *)malloc(bzLineBufPosition); strncpy(bzBufRemainder, bzLineBuf, bzLineBufPosition); } } } } if (bzError != BZ_STREAM_END) { BZ2_bzReadClose(&bzError, bzFp); fprintf(stderr, "\n\t[gchr2] - Error: Bzip2 data could not be uncompressed\n\n"); return -1; } else { BZ2_bzReadGetUnused(&bzError, bzFp, 0, 0); BZ2_bzReadClose(&bzError, bzFp); } free(bzBufRemainder); bzBufRemainder = NULL;
I am very grateful to everyone for their help. It works great.