summaryrefslogtreecommitdiffstats
path: root/zcatgrep.cc
blob: d1e2d815c358ebe44356c154413de669f67b5d6d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/*  Common code for zcat and zgrep
    Copyright (C) 2010-2016 Antonio Diaz Diaz.

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#ifndef O_BINARY
#define O_BINARY 0
#endif


int simple_extension_index( const std::string & name )
  {
  for( int i = 0; i < num_formats; ++i )
    {
    const std::string ext( simple_extensions[i] );
    if( name.size() > ext.size() &&
        name.compare( name.size() - ext.size(), ext.size(), ext ) == 0 )
      return i;
    }
  return -1;
  }


int open_instream( std::string & input_filename, const bool search,
                   const bool no_messages = false )
  {
  int infd = open( input_filename.c_str(), O_RDONLY | O_BINARY );
  if( infd < 0 )
    {
    if( search && simple_extension_index( input_filename ) < 0 )
      {
      for( int i = 0; i < num_formats; ++i )
        if( enabled_format( format_order[i] ) )
          {
          const std::string name( input_filename +
                                  simple_extensions[format_order[i]] );
          infd = open( name.c_str(), O_RDONLY | O_BINARY );
          if( infd >= 0 ) { input_filename = name; break; }
          }
      }
    if( infd < 0 && !no_messages )
      show_error2( "Can't open input file", input_filename.c_str() );
    }
  return infd;
  }