FileIO.c 21.1 KB
Newer Older
1
/*
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
 *  Copyright (C) 2007 Bernd Machenschalk, Jolien Creighton, Reinhard Prix
 *
 *  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 with program; see the file COPYING. If not, write to the
 *  Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 */
19

20
#include <config.h>
21 22

#include <stdarg.h>
23
#include <stdlib.h>
24
#include <string.h>
25
#include <errno.h>
26

27 28 29 30 31 32 33
#ifdef HAVE_SYS_STAT_H
#include <sys/stat.h>
#endif
#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif

34
#include <zlib.h>
35 36
#define ZLIB_ENABLED

37 38
#include <lal/LALStdlib.h>
#include <lal/LALStdio.h>
39 40
#include <lal/LALString.h>
#include <lal/StringInput.h>
41
#include <lal/FileIO.h>
42

43 44 45 46 47
struct tagLALFILE {
  int compression;
  void *fp;
};

48
LALFILE *lalstdin( void )
49
{
50 51 52
  static LALFILE _lalstdin;
  _lalstdin.fp = (void*)stdin;
  return &_lalstdin;
53
}
54
LALFILE *lalstdout( void )
55
{
56 57 58
  static LALFILE _lalstdout;
  _lalstdout.fp = (void*)stdout;
  return &_lalstdout;
59
}
60
LALFILE *lalstderr( void )
61
{
62 63 64
  static LALFILE _lalstderr;
  _lalstderr.fp = (void*)stderr;
  return &_lalstderr;
65 66
}

67 68 69 70 71
/** 'Resolve' a given filename 'fname', returning a file path where the
 *  file can successfully be opened by fopen() using mode='rb'.
 *
 * Return: successful file-path or NULL if failed.
 *
72
 * Resolving uses the following algorithm: if 'fname' contains a
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
 * i) (relative or absolute) path: only tries to open that path directly
 * ii) pure filename: try 1) local dir, then 2) search LAL_DATA_PATH, then 3) try fallbackdir
 *                    return first successful hit
 *
 * Note: it is not an error if the given 'fname' cannot be resolved,
 * this will simply return NULL but xlalErrno will not be set in that case.
 *
 * Note2: successfully resolving an 'fname' doesn't guarantee that the path points
 * to a file, as directories can also be opened in 'rb'.
 *
 * Note3: the returned string is allocated here and must be XLALFree'ed by the caller.
 */
char *
XLALFileResolvePathLong ( const char *fname,	  //!< [in] filename or file-path to resolve
                          const char *fallbackdir //!< [in] directory to try as a last resort (usually PKG_DATA_DIR) [can be NULL]
                          )
{
  XLAL_CHECK_NULL ( fname != NULL, XLAL_EINVAL );

  UINT4 fname_len = strlen ( fname );

  if ( strchr ( fname, '/' ) != NULL )	// any kind of (absolute or relative) path is given -> use only that
    {
      FILE *tmp;
      if ( (tmp = LALFopen ( fname, "rb" )) != NULL ) {
        LALFclose ( tmp );
        return XLALStringDuplicate ( fname );
      } // if found
      else {
        return NULL;
      } // if not found

    } // end: if path given
  else	// if pure filename given: try 1) local directory, then 2) scan LAL_DATA_PATH, then 3) try fallbackdir (if given)
    {
      FILE *tmp;
      char *resolveFname = NULL;

      // ----- Strategy 1: try local directory explicitly
      XLAL_CHECK_NULL ( (resolveFname = XLALMalloc ( fname_len + 2 + 1 )) != NULL, XLAL_ENOMEM );
      sprintf ( resolveFname, "./%s", fname );
      if ( (tmp = LALFopen ( resolveFname, "rb" )) != NULL ) {
        LALFclose ( tmp );
        return resolveFname;
      } // if found

      // ----- Strategy 2: scan LAL_DATA_PATH
      const char *lal_data_path = getenv( "LAL_DATA_PATH" );
      if ( lal_data_path && (strlen (lal_data_path ) > 0) )
        {
          TokenList *subPaths = NULL;
          XLAL_CHECK_NULL ( XLALCreateTokenList ( &subPaths, lal_data_path, ":" ) == XLAL_SUCCESS, XLAL_EFUNC );
          for ( UINT4 i = 0; i < subPaths->nTokens; i ++ )
            {
              const char *subPath_i = subPaths->tokens[i];
              XLAL_CHECK_NULL ( (resolveFname = XLALRealloc ( resolveFname, strlen(subPath_i) + 1 + fname_len + 1 )) != NULL, XLAL_ENOMEM );
              sprintf ( resolveFname, "%s/%s", subPath_i, fname );
              if ( (tmp = LALFopen ( resolveFname, "rb" )) != NULL ) {
                LALFclose ( tmp );
                XLALDestroyTokenList ( subPaths );
                return resolveFname;
              } // if found

            } // for i < nTokens

          XLALDestroyTokenList ( subPaths );

        } // if LAL_DATA_PATH given

      // ----- Strategy 3: try 'fallbackdir' if given
      if ( fallbackdir != NULL )
        {
          XLAL_CHECK_NULL ( (resolveFname = XLALRealloc ( resolveFname, strlen(fallbackdir) + 1 + strlen(fname) + 1 )) != NULL, XLAL_ENOMEM );
          sprintf ( resolveFname, "%s/%s", fallbackdir, fname );
          if ( (tmp = LALFopen ( resolveFname, "rb" )) != NULL ) {
            LALFclose ( tmp );
            return resolveFname;
          } // if found
        } // if fallbackdir

      XLALFree ( resolveFname );

    } // end: if pure filename given

  // nothing worked? that's ok: return NULL without failure!
  return NULL;

} // XLALFileResolvePathLong()

/** Simple wrapper to XLALFileResolvePathLong(), using hardcoded fallbackdir=PKG_DATA_DIR
 */
char *
XLALFileResolvePath ( const char *fname	  //!< [in] filename or file-path to resolve
                      )
{
  return XLALFileResolvePathLong ( fname, PKG_DATA_DIR );
} // XLALFileResolvePath()

171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
/** Read a complete data-file into memory as a string
 */
char *
XLALFileLoad ( const char *path		//!< [in] input filepath
               )
{
  XLAL_CHECK_NULL ( path != NULL, XLAL_EINVAL );

  // check that this is actually a regular file, rather than sth else (eg a directory)
  size_t blobLen;
  XLAL_CHECK_NULL ( XLALFileIsRegularAndGetSize ( path, &blobLen ) == 1, XLAL_EINVAL, "Path '%s' does not point to a regular file!\n", path );

  char *dataBuffer = NULL;
  size_t dataBufferLen = 0;
  size_t numReadTotal = 0;
  LALFILE *fp;
  XLAL_CHECK_NULL ( (fp = XLALFileOpenRead (path)) != NULL, XLAL_EFUNC );

  // read file in blobs the size of the (possibly compressed) file
  int blobCounter = 0;
  while ( ! XLALFileEOF( fp ) )
    {
      dataBufferLen += blobLen;
      if ( (dataBuffer = XLALRealloc ( dataBuffer, dataBufferLen + 1)) == NULL ) {
        XLALFileClose(fp);
196
        XLAL_ERROR_NULL ( XLAL_ENOMEM, "Failed to XLALRealloc(%zu)\n", dataBufferLen+1 );
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
      }
      size_t numRead = XLALFileRead ( dataBuffer + blobCounter*blobLen, sizeof(char), blobLen, fp );
      if ( xlalErrno != XLAL_SUCCESS ) {
        XLALFree ( dataBuffer );
        XLALFileClose(fp);
        XLAL_ERROR_NULL ( XLAL_EFUNC );
      }

      numReadTotal += numRead;

      if ( numRead < blobLen ) {
        break;
      }
      blobCounter ++;

    } // while !eof

  XLALFileClose(fp);

  // adjust buffer to final size of data read
217
  XLAL_CHECK_NULL ( (dataBuffer = XLALRealloc ( dataBuffer, numReadTotal + 1)) != NULL, XLAL_ENOMEM, "Failed to XLALRealloc(%zu)\n", numReadTotal+1 );
218 219 220 221 222 223
  dataBuffer[numReadTotal] = 0;

  return dataBuffer;

} // XLALFileLoad()

224 225
int XLALFileIsCompressed( const char *path )
{
226 227 228 229 230 231
  FILE *fp;
  unsigned char magic[2] = { 0, 0 };
  size_t c;
  if ( ! ( fp = LALFopen( path, "rb" ) ) )
    XLAL_ERROR( XLAL_EIO );
  c = fread( magic, sizeof(*magic), sizeof(magic)/sizeof(*magic), fp );
232
  if (c == 0)
233
    XLAL_ERROR( XLAL_EIO );
234 235
  fclose( fp );
  return magic[0] == 0x1f && magic[1] == 0x8b;
236 237
}

238
LALFILE *XLALFileOpenRead( const char *path )
239
{
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
  int compression;
  LALFILE *file;
  if ( 0 > (compression = XLALFileIsCompressed(path) ) )
    XLAL_ERROR_NULL( XLAL_EIO );
#ifndef ZLIB_ENABLED
  if ( compression ) {
    XLALPrintError( "XLAL Error - %s: Cannot read compressed file\n", __func__ );
    XLAL_ERROR_NULL( XLAL_EIO );
  }
#endif
  if ( ! ( file = XLALMalloc( sizeof(*file ) ) ) )
    XLAL_ERROR_NULL( XLAL_ENOMEM );
  file->compression = compression;
#ifdef ZLIB_ENABLED
  file->fp = compression ? (void*)gzopen( path, "rb" ) : (void*)LALFopen( path, "rb" );
#else
  file->fp = (void*)LALFopen( path, "rb" );
#endif
  if ( ! file->fp ) {
    XLALFree( file );
    XLAL_ERROR_NULL( XLAL_EIO );
  }
  return file;
263 264
}

265
LALFILE *XLALFileOpenAppend( const char *path, int compression )
266
{
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
  LALFILE *file;
  if ( ! ( file = XLALMalloc( sizeof(*file ) ) ) )
    XLAL_ERROR_NULL( XLAL_ENOMEM );
#ifdef ZLIB_ENABLED
  file->fp = compression ? (void*)gzopen( path, "a+" ) : (void*)LALFopen( path, "a+" );
#else
  if ( compression ) {
    XLALPrintWarning( "XLAL Warning - %s: Compression not supported\n", __func__ );
    compression = 0;
  }
  file->fp = (void*)LALFopen( path, "a+" );
#endif
  file->compression = compression;
  if ( ! file->fp ) {
    XLALFree( file );
    XLAL_ERROR_NULL( XLAL_EIO );
  }
  return file;
285 286
}

287
LALFILE *XLALFileOpenWrite( const char *path, int compression )
288
{
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
  LALFILE *file;
  if ( ! ( file = XLALMalloc( sizeof(*file ) ) ) )
    XLAL_ERROR_NULL( XLAL_ENOMEM );
#ifdef ZLIB_ENABLED
  file->fp = compression ? (void*)gzopen( path, "wb" ) : (void*)LALFopen( path, "wb" );
#else
  if ( compression ) {
    XLALPrintWarning( "XLAL Warning - %s: Compression not supported\n", __func__ );
    compression = 0;
  }
  file->fp = (void*)LALFopen( path, "wb" );
#endif
  file->compression = compression;
  if ( ! file->fp ) {
    XLALFree( file );
    XLAL_ERROR_NULL( XLAL_EIO );
  }
  return file;
307 308
}

309
LALFILE *XLALFileOpen( const char *path, const char *mode )
310
{
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
  int compression;
  char *ext;
  switch ( *mode ) {
  case 'r':
    return XLALFileOpenRead( path );
  case 'w':
    /* check if filename ends in .gz */
    ext = strrchr( path, '.' );
    compression = ext ? ! strcmp( ext, ".gz" ) : 0;
    return XLALFileOpenWrite( path, compression );
  default:
    break; /* fall-out */
  }
  /* error if code gets here */
  XLAL_ERROR_NULL( XLAL_EINVAL );
326 327
}

328
int XLALFileClose( LALFILE *file )
329
{
330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
  /* this routine acts as a no-op if the file is NULL */
  /* this behavior is different from BSD fclose */
  if ( file ) {
    int c;
    if ( ! file->fp )
      XLAL_ERROR( XLAL_EINVAL );
#ifdef ZLIB_ENABLED
    c = file->compression ? gzclose(((gzFile)file->fp)) : fclose(((FILE*)file->fp));
#else
    c = fclose(((FILE*)file->fp));
#endif
    if ( c == EOF )
      XLAL_ERROR( XLAL_EIO );
    XLALFree( file );
  }
  return 0;
346 347 348 349
}

size_t XLALFileRead( void *ptr, size_t size, size_t nobj, LALFILE *file )
{
350 351 352 353 354 355 356 357 358 359 360
  size_t c;
  if ( ! file )
    XLAL_ERROR( XLAL_EFAULT );
#ifdef ZLIB_ENABLED
  c = file->compression ? (size_t)gzread( ((gzFile)file->fp), ptr, size * nobj ) : fread( ptr, size, nobj, ((FILE*)file->fp) );
#else
  c = fread( ptr, size, nobj, ((FILE*)file->fp) );
#endif
  if ( c == (size_t)(-1) || (file->compression == 0 && ferror((FILE*)(file->fp))) )
    XLAL_ERROR( XLAL_EIO );
  return c;
361 362 363 364
}

size_t XLALFileWrite( const void *ptr, size_t size, size_t nobj, LALFILE *file )
{
365 366 367 368 369 370 371 372 373 374 375
  size_t c;
  if ( ! file )
    XLAL_ERROR( XLAL_EFAULT );
#ifdef ZLIB_ENABLED
  c = file->compression ? (size_t)gzwrite( ((gzFile)file->fp), ptr, size * nobj ) : fwrite( ptr, size, nobj, ((FILE*)file->fp) );
#else
  c = fwrite( ptr, size, nobj, (FILE*)(file->fp) );
#endif
  if ( c == 0 || (file->compression == 0 && ferror((FILE*)(file->fp))) )
    XLAL_ERROR( XLAL_EIO );
  return c;
376 377 378 379
}

int XLALFileGetc( LALFILE *file )
{
380 381 382 383 384 385 386 387 388
  int c;
  if ( ! file )
    XLAL_ERROR( XLAL_EFAULT );
#ifdef ZLIB_ENABLED
  c = file->compression ? gzgetc(((gzFile)file->fp)) : fgetc(((FILE*)file->fp));
#else
  c = fgetc(((FILE*)file->fp));
#endif
  return c;
389 390 391 392
}

int XLALFilePutc( int c, LALFILE *file )
{
393 394 395 396 397 398 399 400 401 402 403
  int result;
  if ( ! file )
    XLAL_ERROR( XLAL_EFAULT );
#ifdef ZLIB_ENABLED
  result = file->compression ? gzputc(((gzFile)file->fp), c) : fputc(c, ((FILE*)file->fp));
#else
  result = fputc(c, (FILE*)(file->fp));
#endif
  if ( result == -1 )
    XLAL_ERROR( XLAL_EIO );
  return result;
404 405 406 407
}

char * XLALFileGets( char * s, int size, LALFILE *file )
{
408 409 410 411 412 413 414 415 416
  char *c;
  if ( ! file )
    XLAL_ERROR_NULL( XLAL_EFAULT );
#ifdef ZLIB_ENABLED
  c = file->compression ? gzgets( ((gzFile)file->fp), s, size ) : fgets( s, size, ((FILE*)file->fp) );
#else
  c = fgets( s, size, ((FILE*)file->fp) );
#endif
  return c;
417 418
}

419
int XLALFilePuts( const char * s, LALFILE *file )
420
{
421 422 423 424 425
  if ( ! file )
    XLAL_ERROR( XLAL_EFAULT );
  if ( 0 > (int)XLALFileWrite( s, sizeof(*s), strlen(s), file ) )
    XLAL_ERROR( XLAL_EFUNC );
  return 0;
426 427 428 429
}

int XLALFileVPrintf( LALFILE *file, const char *fmt, va_list ap )
{
430
  char buf[32768];
431 432 433 434
  int len;
  int c;
  if ( ! file )
    XLAL_ERROR( XLAL_EFAULT );
435
  len = vsnprintf( buf, sizeof(buf), fmt, ap );
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
  if ( len < 0 )
    XLAL_ERROR( XLAL_EFAILED );
  if ( len >= (int)sizeof(buf) ) { /* buffer is too small */
    char *s;
    s = XLALMalloc( len + 1 );
    if ( !s )
      XLAL_ERROR( XLAL_ENOMEM );
    len = vsnprintf( s, len + 1, fmt, ap );
    c = XLALFilePuts( s, file );
    XLALFree( s );
  } else {
    c = XLALFilePuts( buf, file );
  }
  if ( c < 0 )
    XLAL_ERROR( XLAL_EFUNC );
  return len;
452 453 454 455
}

int XLALFilePrintf( LALFILE *file, const char *fmt, ... )
{
456 457 458 459 460 461 462 463
  int c;
  va_list ap;
  va_start( ap, fmt );
  c = XLALFileVPrintf( file, fmt, ap );
  va_end( ap );
  if ( c < 0 )
    XLAL_ERROR( XLAL_EFUNC );
  return c;
464 465 466 467 468
}


int XLALFileFlush( LALFILE *file )
{
469 470 471 472 473 474 475 476 477 478 479
  int c;
  if ( ! file )
    XLAL_ERROR( XLAL_EFAULT );
#ifdef ZLIB_ENABLED
  c = file->compression ? gzflush(((gzFile)file->fp), Z_FULL_FLUSH) : fflush(((FILE*)file->fp));
#else
  c = fflush(((FILE*)file->fp));
#endif
  if ( c == -1 )
    XLAL_ERROR( XLAL_EIO );
  return c;
480 481 482 483
}

int XLALFileSeek( LALFILE *file, long offset, int whence )
{
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
  int c;
  if ( ! file )
    XLAL_ERROR( XLAL_EFAULT );
#ifdef ZLIB_ENABLED
  if ( file->compression && whence == SEEK_END ) {
    XLALPrintError( "XLAL Error - %s: SEEK_END not supported with compressed files\n", __func__ );
    XLAL_ERROR( XLAL_EINVAL );
  }
  c = file->compression ? gzseek(((gzFile)file->fp), offset, whence) : fseek(((FILE*)file->fp), offset, whence);
#else
  c = fseek(((FILE*)file->fp), offset, whence);
#endif
  if ( c == -1 )
    XLAL_ERROR( XLAL_EIO );
  return 0;
499 500 501 502
}

long XLALFileTell( LALFILE *file )
{
503 504 505 506 507 508 509 510 511 512
  long c;
  if ( ! file )
    XLAL_ERROR( XLAL_EFAULT );
#ifdef ZLIB_ENABLED
  c = file->compression ? (long)gztell(((gzFile)file->fp)) : ftell(((FILE*)file->fp));
#else
  c = ftell(((FILE*)file->fp));
#endif
  if ( c == -1 )
    XLAL_ERROR( XLAL_EIO );
513
  return c;
514 515 516 517
}

void XLALFileRewind( LALFILE *file )
{
518 519 520 521 522 523 524 525
  if ( ! file )
    XLAL_ERROR_VOID( XLAL_EFAULT );
#ifdef ZLIB_ENABLED
  file->compression ? (void)gzrewind(((gzFile)file->fp)) : rewind(((FILE*)file->fp));
#else
  rewind(((FILE*)file->fp));
#endif
  return;
526 527 528 529
}

int XLALFileEOF( LALFILE *file )
{
530 531 532 533 534 535 536 537 538
  int c;
  if ( ! file )
    XLAL_ERROR( XLAL_EFAULT );
#ifdef ZLIB_ENABLED
  c = file->compression ? gzeof(((gzFile)file->fp)) : feof((FILE*)(file->fp));
#else
  c = feof((FILE*)(file->fp));
#endif
  return c;
539
}
540

541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604
/** Check if path points to a 'regular file', rather than a directory or sth else.
 * and also return the size of the given file.
 *
 * This is simply a wrapper to stat(), and S_ISREG()
 * and could be easily generalized along those lines to test for directories etc.
 *
 * return an error if stat() was unavailable
 * return 1 for true, 0 for false, -1 on error
 */
int
XLALFileIsRegularAndGetSize ( const char *path,	//!< [in] path to file
                              size_t *fileLen	//!< [out] size in bytes of file
                              )
{
#ifndef HAVE_STAT
  XLAL_ERROR ( XLAL_EFAILED, "No implementation of function stat() available, which is required here!\n");
#else
  XLAL_CHECK ( path != NULL, XLAL_EINVAL );

  struct stat sb;
  XLAL_CHECK ( stat( path, &sb) != -1, XLAL_EIO, "stat() failed: perror = '%s'\n", strerror(errno) );

  if ( fileLen ) {	// optional output argument
    (*fileLen) = (size_t)sb.st_size;
  }

  return (S_ISREG(sb.st_mode));
#endif

} // XLALFileIsRegularAndGetSize()


/** Check if given file is 'regular' (rather than a directory or sth else)
 *
 * This is a simple wrapper to XLALFileIsRegularAndGetSize().
 *
 * Return 1 for true, 0 for false, -1 on error
 */
int
XLALFileIsRegular ( const char *path	//!< [in] path to file
                    )
{
  return XLALFileIsRegularAndGetSize ( path, NULL );
} // XLALFileIsRegular()


/** Return the size of given file in bytes.
 *
 * This is simply a wrapper to XLALFileIsRegularAndGetSize()
 *
 * Returns (size_t)-1 on error
 */
size_t
XLALFileSize ( const char *path		//!< [in] path to file
               )
{
  size_t size;

  XLAL_CHECK ( XLALFileIsRegularAndGetSize ( path, &size ) != -1, XLAL_EFUNC );

  return size;

} // XLALFileSize()

605 606
/**
 * \brief Use gzip to compress a text file
607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630
 * This function will use the gzip compression routines in \c zlib to compress a text file. The compressed file will
 * have the extension ".gz" and the original uncompressed file will be removed.
 *
 * \param filename [in] The input text file.
 */
int XLALGzipTextFile( const char *filename ){
  char *memblock = NULL; /* memory block to read data into */
  long pos;
  char *outname = NULL;

  LALFILE *fp = NULL; /* input file pointer */
  LALFILE *fg = NULL; /* output gzipped file pointer */

  /* open file for reading and work out its size */
  if( (fp = XLALFileOpen( filename, "rb" )) == NULL ){
    XLALPrintError ("%s: Unable to open file %s.\n", __func__, filename );
    XLAL_ERROR( XLAL_EIO );
  }

  XLALFileSeek( fp, 0, SEEK_END ); /* go to end of the file */
  pos = XLALFileTell( fp ); /* get the position of the file pointer */
  XLALFileRewind( fp ); /* return the file pointer to the start of the file */

  /* allocate memory to read in data */
631
  memblock = XLALMalloc( pos + 1);
632 633 634 635 636 637 638 639 640 641 642

  if ( !memblock ){
    XLALPrintError ("%s: Unable to allocate memory for reading file.\n", __func__ );
    XLAL_ERROR ( XLAL_ENOMEM );
  }

  /* read in data */
  if ( XLALFileRead( memblock, pos, 1, fp ) == 0 ){
    XLALPrintError ("%s: Unable to read in file.\n", __func__ );
    XLAL_ERROR( XLAL_EIO );
  }
643
  memblock[pos] = 0; // properly 0-terminate string
644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682

  XLALFileClose( fp );

  /* create output name with .gz appended */
  if ( (outname = XLALCalloc(strlen(filename)+4, 1)) == NULL)      /* we need local copy */{
    XLAL_ERROR ( XLAL_ENOMEM );
  }

  strcpy(outname, filename);
  strcat(outname, ".gz"); /* add the extension */

  if ( !outname ){
    XLALPrintError("%s: Unable to create output filename.\n", __func__ );
    XLAL_ERROR( XLAL_EFAULT );
  }

  /* open output gzip file */
  if ( (fg = XLALFileOpen( outname, "wb" )) == NULL ){
    XLALPrintError ("%s: Unable to open output file %s.\n", __func__, outname );
    XLAL_ERROR( XLAL_EIO );
  }

  if ( XLALFilePuts( memblock, fg ) != 0 ){
    XLALPrintError ("%s: Unable to output gzipped data.\n", __func__ );
    XLAL_ERROR( XLAL_EIO );
  }

  XLALFileClose( fg );

  /* remove original file */
  if ( remove( filename ) == -1 ){
    XLALPrintError ("%s: Unable to remove original text file.\n", __func__ );
    XLAL_ERROR( XLAL_EFAILED );
  }

  return XLAL_SUCCESS;
}


683 684
/**
 * \brief Use gzip to uncompress a compressed text file
685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716
 *
 * This function will use the gzip compression routines in \c zlib to uncompress a gzipped text file. The compressed
 * file should have the ".gz" extension otherwise it will be rejected. The output will have the same filename with the
 * ".gz" extension removed. The compressed file will be removed.
 *
 * Note: \c gzopen will check the file's "magic number" to see if it is a gzipped file. If it's not a gzipped file it
 * will still open the file for reading as a standard file.
 *
 * \param filename [in] The input gzipped text file.
 */
int XLALGunzipTextFile( const char *filename ){
  CHAR *memblock = NULL; /* memory block to read data into */
  CHAR *outname = NULL;
  CHAR *gzpos = NULL;

  LALFILE *fp = NULL; /* output file pointer */
  LALFILE *fg = NULL; /* input gzipped file pointer */
  size_t n;

  /* create output file name by striping .gz from the input file name */
  if ( (gzpos = strstr(filename, ".gz")) == NULL ){
    XLALPrintError ("%s: File %s does not contain the .gz extension.\n", __func__, filename );
    XLAL_ERROR ( XLAL_EIO );
  }

  n = gzpos-filename;
  outname = XLALMalloc( sizeof(CHAR)*(n+1) );

  if ( ( outname = strncpy(outname, filename, n) ) == NULL ){
    XLALPrintError ("%s: Unable to strip extension from file string.\n", __func__ );
    XLAL_ERROR ( XLAL_EIO );
  }
717
  outname[n] = 0;
718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748

  /* open gzipped file for reading */
  if ( (fg = XLALFileOpen(filename, "rb")) == NULL ){
    XLALPrintError ("%s: Unable to open gzipped file %s.\n", __func__, filename );
    XLAL_ERROR ( XLAL_EIO );
  }

  /* open output text file */
  if ( (fp = XLALFileOpen(outname, "w")) == NULL ){
    XLALPrintError ("%s: Unable to open output file %s.\n", __func__, outname );
    XLAL_ERROR ( XLAL_EIO );
  }

  /* allocate memory for a single char */
  memblock = XLALMalloc( sizeof(CHAR) );

  /* read in gzipped data one byte at a time and output to text file */
  while( ( memblock = XLALFileGets(memblock, 2, fg) ) != NULL ){ XLALFilePrintf(fp, "%s", memblock); }

  /* close files */
  XLALFileClose( fg );
  XLALFileClose( fp );

  /* remove original file */
  if ( remove( filename ) == -1 ){
    XLALPrintError ("%s: Unable to remove original gzipped file.\n", __func__ );
    XLAL_ERROR( XLAL_EFAILED );
  }

  return XLAL_SUCCESS;
}