Reputation: 302
I used to use popen(("zcat " + filename).c_str(), "r")
to read zipped text files. However, I need read zipped binary file this time. I tried popen(("zcat " + filename).c_str(), "rb")
but it failed as the return value is NULL even if the file does exist.
May I know why the way fails? I can guarantee the filename is properly defined, no special characters and the file does exist. The similar way works when I read zipped text files.
May I know what should be the correct way to do that?
Upvotes: 0
Views: 920
Reputation: 38217
"rb"
isn't a valid mode for popen
. If you read the man page for popen
, you'll see it says:
FILE *popen(const char *command, const char *type);
[...]
The
type
argument is a pointer to a null-terminated string which must contain either the letter'r'
for reading or the letter'w'
for writing.[...]
If you look at the POSIX documentation for fopen
, it says (regarding the mode string):
The character
'b'
shall have no effect, but is allowed for ISO C standard conformance.
Thus, on a POSIX-ish system (like Linux), you don't need to specify binary mode when opening files, especially when using popen
. Any FILE*
you get back from popen
will always be opened in binary mode.
If you decide to use zlib instead of popen("zcat", ...)
(as other suggest, and I might recommend) there's a lot of good documentation, and I have personally found the zpipe.c
demo very helpful.
Upvotes: 2