问题
I need to unzip a file while running a C++ program (as described in Waiting for unzip to finish before carrying on C++ code on a RedHat machine)
To do this I currently do something like this:
system("unzip /usr/bin/File/ZippedFile.gz -d /usr/bin/File/)
Which unzips "/usr/bin/File/ZippedFile.gz" to "/usr/bin/File/ZippedFile" with no problems.
This works fine. However I have noticed that many people seem to say that using
system()
is taboo.
People don't seem to like it as due to security and system resources (as discussed here: http://www.cplusplus.com/forum/articles/11153/).
But as I want the program to wait until the unzip is complete, is there a viable alternative?
回答1:
You can use plain zlib, or the boost::iostream
gzip facility.
System isn't wrong per se, but you could also write a replacement for it which doesn't use the shell with fork
, exec
, wait
and mkstemp
. This is cumbersome though. Using boost::gzip_decompressor
is the best C++ option to me if you decompress single files. Forking and friends may be better if you need to unzip a directory. Be sure to read about mkstemp
.
For a crash course on fork and exec family: http://www.yolinux.com/TUTORIALS/ForkExecProcesses.html
For an example of using wait
for your child to terminate: http://support.sas.com/documentation/onlinedoc/sasc/doc/lr2/wait.htm
For reference about creating a temporary directory: http://www.gnu.org/s/hello/manual/libc/Temporary-Files.html
回答2:
Yep, it is bad practice for various reasons(security, portability, etc). You need to get a zipping library(a google search give me something like http://www.firstobject.com/easy-zlib-c++-xml-compression.htm or even the library used to build 'unzip' if it's free, but there must be loads out there) and then use it and if you need to do both parallelly then introduce threads. A bit work I agree, but that's better in practise than using the system() call.
来源:https://stackoverflow.com/questions/7022990/unzipping-a-file-from-c-on-redhat-alternatives-to-system