1

I have a log_date.txt file that I wrote some C code around to parse and reduce it. I parse it by using fgets( buffer, 1024, fp ) to read each line into my buffer character array. Everything is based around a text file with newlines, and I read text line by line.

In keeping these logs over time, each one has had gzip -9 done on it resulting in log_20200101.txt.gz

Imagine having a file saved every day and when running my C code to read any chosen one you would have to manually do a gunzip log_20200101.txt.gz beforehand, and when done re-gzip it. Is there a way in C to do an fopen and continue to use all my fgets() but have it happen on a .gz file?

2
  • You're serious? The answer is a flat "no". To read the file as text, you'll have to decompress it first. There may be libraries available that will let you decompress the file to a temp file or stream first, but that seems kind of onerous. I'm just curioius why you don't just create an enclosing script that will decompress the file, then invoke your log file processor against it, and remove the uncompressed file when you're done. That would take three lines in just about any scripting or shell language that I'm aware of.
    – Curt
    Commented Jan 27, 2020 at 19:54
  • yes, and don't call me serious.
    – ron
    Commented Jan 27, 2020 at 20:12

1 Answer 1

2

boom

works inherently on both log.txt and log.txt.gz

    # include <stdio.h>
    # include <stdlib.h>
    # include <zlib.h>

    # define LL 8192   /* line length maximum */

    int main ( int argc, char *argv[] )
    {
       gzFile fp;
       char line[LL];

       fp = gzopen( "log.txt.gz", "r" );

       gzgets( fp, line, LL );

       while ( ! gzeof( fp ) )
       {
          printf("%s", line );
          gzgets( fp, line, LL );
       }

       gzclose( fp );
       return 0;
    }
2
  • 1
    gcc yourprogram.c -lz
    – ron
    Commented Jan 27, 2020 at 20:37
  • Well, there's this...
    – Curt
    Commented Jan 27, 2020 at 21:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.