Skip to content

Instantly share code, notes, and snippets.

@molpopgen
Created February 20, 2014 20:45
Show Gist options
  • Save molpopgen/9122845 to your computer and use it in GitHub Desktop.
Save molpopgen/9122845 to your computer and use it in GitHub Desktop.
A C++ function to check that a file both exists and is in .gz format.
/*
A function to check that a file both exists and is in .gz format.
It is done the easy way, using only C++ constructs instead of any lower-level calls
Requires the boost iostreams library
Programs compiled using this function need -lboost_iostreams
*/
//Required headers
#include <iostream>
#include <boost/iostreams/filter/gzip.hpp>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/device/file.hpp>
bool isgz(const char * filename)
{
//first, check that it exists
std::ifstream in(filename);
if(! in)
{
return false;
}
in.close();
/*
If the file is not .gz and we try
to read from it using boost's filtering_istream
classes, an exception will be thrown.
Therefore, catching the exception tells
you the file is not .gz.
*/
boost::iostreams::filtering_istream gzin;
gzin.push(boost::iostreams::gzip_compressor());
gzin.push(boost::iostreams::file_source(filename),std::ios_base::in | std::ios_base::binary);
char c;
try
{
gzin >> c;
}
catch ( boost::iostreams::gzip_error & e )
{
gzin.pop();
return false;
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment