Пример #1
0
/* THIS NEEDS ADJUSTING for >2Gb records - CALVIN */
int
unf_position (FILE *fd, unit *ftnunit)
{
    /* Last I/O has an error, must make sure that the file
    pointer is positioned at the right place, i.e. must be
    between two unformatted records */
    ftnll             pos = FTELL(fd);
    /* Use local 'reclen' instead of global 'ftnunit->f77reclen' to avoid
    side effect
    */
    int reclen_short;

    if (ftnunit->uerror == EOF) {
        ftnunit->uerror = 0;
        return(0);
    }
    ftnunit->uerror = 0;
    fseek (fd, 0, 0);
    while (FTELL (fd) < pos) {
        /* need to change this for > 2gb records DLAI */
        fread ((char *) &reclen_short, sizeof (int), 1, fd);
        fseek (fd, (long) (reclen_short + sizeof (int)), SEEK_CUR);
    }
    return (0);
}
Пример #2
0
streamsize stdio_istreambuf::showmanyc() {
  if (feof(_M_file))
    return -1;
  else {
    int fd = _FILE_fd(_M_file);
#ifdef _STLP_WCE
   (fd); // prevent warning about unused variable
// not sure if i can mix win32 io mode with ftell but time will show
// cannot use WIN32_IO implementation since missing stat
    streamsize tmp = FTELL(_M_file);
    FSEEK(_M_file, 0, SEEK_END);
    streamoff size= FTELL(_M_file)-tmp;
    FSEEK(_M_file, tmp, SEEK_SET);
#elif defined (_STLP_USE_WIN32_IO)
    // in this case, __file_size works with Win32 fh , not libc one
    streamoff size;
    struct stat buf;
    if(FSTAT(fd, &buf) == 0 && ( _S_IFREG & buf.st_mode ) )
      size = ( buf.st_size > 0  ? buf.st_size : 0);
    else
      size = 0;
#else
    streamoff size = __file_size(fd);
#endif
    // fbp : we can use ftell as this flavour always use stdio.
    streamsize pos = FTELL(_M_file);
    return pos >= 0 && size > pos ? size - pos : 0;
  }
}
Пример #3
0
streamoff __file_size(FILE* f) {
    streamoff old_ofs = FTELL(f);
    FSEEK(f, 0, SEEK_END);
    streamoff size = FTELL(f);
    FSEEK(f, old_ofs, SEEK_SET);
    return size;
}
Пример #4
0
FskErr KplFileGetSize(KplFile fref, KplInt64 *size)
{
	FILEOFFSET	pos, end;
	FskErr err = kFskErrNone;
	int ret;

	ret = FTELL(fref->theFile);
	if (ret < 0) goto bail;
	pos = ret;
	ret = FSEEK(fref->theFile, 0, SEEK_END);
	if (ret < 0) goto bail;
	ret = FTELL(fref->theFile);
	if (ret < 0) goto bail;
	end = ret;
	ret = FSEEK(fref->theFile, pos, SEEK_SET);
	if (ret < 0) goto bail;

	fref->flushBeforeRead = false;
	fref->flushBeforeWrite = false;

	if (size)
		*size = end;

bail:
	if (ret < 0) {
		FskKplFilesPrintfDebug("## FileGetSize failed -- errno %d\n", errno);
		err = errnoToFskErr(errno);
	}

	return err;
}
Пример #5
0
// ---------------------------------------------------------------------
FskErr FskFSFileGetSize(FskFSFile fref, FskInt64 *size) {
	FILEOFFSET	pos, end;
	FskErr err = kFskErrNone;
	int	ret;

	ret = FTELL(fref->theFile);
	if (ret < 0) goto bail;

	pos = ret;
	FSEEK(fref->theFile, 0, SEEK_END);
	ret = FTELL(fref->theFile);
	if (ret < 0) goto bail;

	end = ret;
	ret = FSEEK(fref->theFile, pos, SEEK_SET);

	fref->flushBeforeRead = false;
	fref->flushBeforeWrite = false;

	if (size)
		*size = end;

bail:
	if (ret < 0)
		err = errnoToFskErr(errno);

	return err;
}
Пример #6
0
static size_t load_size(FILE *file)
{
	FOFFT old = FTELL(file);
	FOFFT pos;
	size_t ret = 0;

	if ((old == (FOFFT)-1) ||
	    (FSEEK(file, 0, SEEK_END) == -1))
		return 0;
	if (((pos = FTELL(file)) != (FOFFT)-1) && (pos >= old))
		ret = (size_t)(pos - old);
	FSEEK(file, old, SEEK_SET);
	return ret;
}
Пример #7
0
	char* bcLoadTextFile(const char* filename) {

		FILE* file;
		fopen_s(&file, filename, "rt");
		unsigned int size = 0;
		char* data;
		if (file) {

			FSEEK(file, 0, SEEK_END);
			size = FTELL(file);
			FSEEK(file, 0, SEEK_SET);

			data = new char[size+1];
			memset(data, 0, size + 1);
			FREAD(data, size, file);

			fclose(file);

			return data;
		} else {
			LOG("Failed To Open File: %s\n", filename);
		}
		
		return nullptr;
	}
Пример #8
0
// Wrapper for lseek or the like.
streamoff _Filebuf_base::_M_seek(streamoff offset, ios_base::seekdir dir)
{
  int whence;

  switch ( dir ) {
    case ios_base::beg:
      if (offset < 0 /* || offset > _M_file_size() */ )
        return streamoff(-1);
      whence = SEEK_SET;
      break;
    case ios_base::cur:
      whence = SEEK_CUR;
      break;
    case ios_base::end:
      if (/* offset > 0 || */  -offset > _M_file_size() )
        return streamoff(-1);
      whence = SEEK_END;
      break;
    default:
      return streamoff(-1);
  }

  if ( FSEEK(_M_file, offset, whence) == 0 ) {
    return FTELL(_M_file);
  }

  return streamoff(-1);
}
Пример #9
0
//////////////////////////////////////////////////////////////////////////////////////////
// Set the new absolute write position
XsensResultValue Cmt1f::setWritePos(const CmtFilePos pos)
{
	if (!m_isOpen)
		return m_lastResult = XRV_NOFILEOPEN;
	if (m_readOnly)
		return m_lastResult = XRV_READONLY;

	if (pos == -1)
	{
		if (m_reading)
			m_reading = false;
		FSEEK_R(0);
		m_writePos = FTELL();
	}
	else
	{
		if (m_writePos != pos)
		{
			m_writePos = pos;
			if (!m_reading)
				FSEEK(m_writePos);
		}
	}

	return m_lastResult = XRV_OK;
}
Пример #10
0
integer e_rdue(Void)
{
	if(f__curunit->url==1 || f__recpos==f__curunit->url)
		return(0);
	FSEEK(f__cf,(OFF_T)(f__curunit->url-f__recpos),SEEK_CUR);
	if(FTELL(f__cf)%f__curunit->url)
		err(f__elist->cierr,200,"syserr");
	return(0);
}
Пример #11
0
/* Truncate a file using ftruncate rather than fork/exec of /bin/cp.
  #1951 sjc 10Dec87 */
ftnint
t_runc (unit *ftnunit, flag xerr) {
   extern void     exit();	/* DAG -- added */
#if 0 /* not used. */
   char            buf[128], nm[16];
   FILE           *tmp;
   int             n, m;
   int             fd;
#endif

#ifdef _BSD
   off_t           ftell();

#endif				/* _BSD */
#if defined  (_SYSV) || defined(_SYSTYPE_SVR4)
#ifndef sgi
   long            ftell();

#endif
#endif				/* SYSV */

   ftnll            loc, len;

   if (ftnunit->uacc == DIRECT)
      return (0);		/* don't truncate direct files */

   if (ftnunit->useek == 0 || ftnunit->ufnm == NULL)
      return (0);

   /* do not truncate "/dev/null" */
   if (strncmp("/dev/null", ftnunit->ufnm, 9) == 0)
      return (0);

   loc = FTELL (ftnunit->ufd);
   (void) fseek (ftnunit->ufd, 0L, 2);
   len = FTELL (ftnunit->ufd);
   /* if ftell() fails then ignore the pipe/device */
   if (loc == len || loc < 0)
      return (0);
   if (TRUNCATE (ftnunit->ufnm, loc))
      err (xerr, 111, "endfile");
   (void) FSEEK (ftnunit->ufd, loc, 0);
   return 0;
}
Пример #12
0
int factor_vm::safe_ftell(FILE* stream) {
  off_t offset;
  for (;;) {
    if ((offset = FTELL(stream)) == -1)
      io_error_if_not_EINTR();
    else
      break;
  }
  return offset;
}
Пример #13
0
integer e_wsue(Void)
{	OFF_T loc;
	fwrite((char *)&f__reclen,sizeof(uiolen),1,f__cf);
#ifdef ALWAYS_FLUSH
	if (fflush(f__cf))
		err(f__elist->cierr, errno, "write end");
#endif
	loc=FTELL(f__cf);
	FSEEK(f__cf,f__recloc,SEEK_SET);
	fwrite((char *)&f__reclen,sizeof(uiolen),1,f__cf);
	FSEEK(f__cf,loc,SEEK_SET);
	return(0);
}
Пример #14
0
Файл: sue.c Проект: Sciumo/f2c
integer s_wsue(cilist *a)
{
	int n;
	if(!f__init) f_init();
	if(n=c_sue(a)) return(n);
	f__reading=0;
	f__reclen=0;
	if(f__curunit->uwrt != 1 && f__nowwriting(f__curunit))
		err(a->cierr, errno, "write start");
	f__recloc=FTELL(f__cf);
	FSEEK(f__cf,(OFF_T)sizeof(uiolen),SEEK_CUR);
	return(0);
}
Пример #15
0
//////////////////////////////////////////////////////////////////////////////////////////
// Open a file.
XsensResultValue Cmt1f::open(const char* filename, const bool create, const bool readOnly)
{
	if (m_isOpen)
		return m_lastResult = XRV_ALREADYOPEN;

	//! \test does this work for non-existing files? Or do we need a check and create?
	m_readOnly = readOnly;
	if (readOnly)
		m_handle = fopen(filename, "rb");	// open for read only (r)
	else
		m_handle = fopen(filename, "r+b");	// open for update (r/w)
	if (m_handle == NULL)
	{
		if (create)
			m_handle = fopen(filename, "w+b");	// create for update (r/w)
		else
		{
			m_handle = fopen(filename, "rb");	// open for read only (r)
			m_readOnly = true;
		}
	}
	if (m_handle == NULL)
		return m_lastResult = XRV_INPUTCANNOTBEOPENED;

	#ifdef _WIN32
		if (_fullpath(m_filename,filename,CMT_MAX_FILENAME_LENGTH) == NULL)
		{
			fclose(m_handle);
			return m_lastResult = XRV_INVALIDPARAM;
		}
	#else
	    // use the same trick again.
		if (realpath(filename, m_filename) == NULL)
		{
		    fclose(m_handle);
		    return m_lastResult = XRV_INVALIDPARAM;
		}
	#endif
	mbstowcs(m_filename_w,m_filename,CMT_MAX_FILENAME_LENGTH);
	m_unicode = false;

	m_isOpen = true;
	m_readPos = 0;
	m_writePos = 0;
	m_reading = true;
	FSEEK_R(0);
	m_fileSize = FTELL();
	FSEEK(0);
	return (m_lastResult = XRV_OK);
}
Пример #16
0
//////////////////////////////////////////////////////////////////////////////////////////
// Open a file.
XsensResultValue Cmt1f::open(const wchar_t* filename, const bool create, const bool readOnly)
{
	if (m_isOpen)
		return m_lastResult = XRV_ALREADYOPEN;

#ifdef _WIN32
	//! \test does this work for non-existing files? Or do we need a check and create?
	m_readOnly = readOnly;
	if (readOnly)
		m_handle = _wfopen(filename, L"rb");	// open for read only (r)
	else
		m_handle = _wfopen(filename, L"r+b");	// open for update (r/w)
	if (m_handle == NULL)
	{
		if (create)
			m_handle = _wfopen(filename, L"w+b");	// create for update (r/w)
		else
		{
			m_handle = _wfopen(filename, L"rb");	// open for read only (r)
			m_readOnly = true;
		}
	}
	if (m_handle == NULL)
		return m_lastResult = XRV_INPUTCANNOTBEOPENED;

	if (_wfullpath(m_filename_w,filename,CMT_MAX_FILENAME_LENGTH) == NULL)
	{
		fclose(m_handle);
		return m_lastResult = XRV_INVALIDPARAM;
	}
	wcstombs(m_filename,m_filename_w,CMT_MAX_FILENAME_LENGTH);

	m_isOpen = true;
	m_readPos = 0;
	m_writePos = 0;
	m_reading = true;
	FSEEK_R(0);
	m_fileSize = FTELL();
	FSEEK(0);
#else
	char tFilename[CMT_MAX_FILENAME_LENGTH*2];
	wcstombs(tFilename,filename,CMT_MAX_FILENAME_LENGTH*2);
	XsensResultValue res = open(tFilename,create,readOnly);
	if (res != XRV_OK)
		return res;
#endif
	m_unicode = true;
	return m_lastResult = XRV_OK;
}
Пример #17
0
osd_file *osd_fopen(int pathtype, int pathindex, const char *filename,
                    const char *mode, osd_file_error *error)
{
    char fullpath[1024];
    osd_file *file;
    int i;

    /* find an empty file pointer */
    for (i = 0; i < MAX_OPEN_FILES; i++)
        if (openfile[i].fileptr == NULL)
            break;
    if (i == MAX_OPEN_FILES)
        goto error;

    /* zap the file record */
    file = &openfile[i];
    memset(file, 0, sizeof(*file));

    /* compose the full path */
    compose_path(fullpath, sizeof(fullpath), pathtype, pathindex, filename);

    /* attempt to open the file */
    file->fileptr = fopen(fullpath, mode);
    if (file->fileptr == NULL)
    {
        /* if it's read-only, or if the path exists, then that's final */
        if (!(strchr(mode, 'w')) || errno != EACCES)
            goto error;

        /* create the path and try again */
        create_path(fullpath, TRUE);
        file->fileptr = fopen(fullpath, mode);

        /* if that doesn't work, we give up */
        if (file->fileptr == NULL)
            goto error;
    }

    /* get the file size */
    FSEEK(file->fileptr, 0, SEEK_END);
    file->end = FTELL(file->fileptr);
    rewind(file->fileptr);
    *error = FILEERR_SUCCESS;
    return file;

error:
    *error = get_last_fileerror();
    return NULL;
}
Пример #18
0
unsigned char get_symbol(int select) {
  long code = 0;
  int length;
  int index;

  for (length = 0; length < 16; length++) {
    code = (2 * code) | get_one_bit();
    if (code <= MaxCode[select][length]) { break; }
  }
  index = ValPtr[select][length] + code - MinCode[select][length];

  if (index < MAX_SIZE(select / 2)) { return HTable[select][index]; }
  ERR("%ld:\tWARNING:\tOverflowing symbol table !\n", FTELL());
  return 0;
}
Пример #19
0
FskErr KplFileGetPosition(KplFile fref, KplInt64 *position)
{
	FILEOFFSET pos;

	if (!fref) return kFskErrInvalidParameter;

	pos = FTELL(fref->theFile);
	if (pos == -1) return errnoToFskErr(errno);

	*position = pos;

	if (*position != pos) return kFskErrOutOfRange;

	return kFskErrNone;
}
Пример #20
0
//////////////////////////////////////////////////////////////////////////////////////////
// Write data to the end of the file.
XsensResultValue Cmt1f::appendData(const uint32_t length, const void* data)
{
	if (!m_isOpen) return m_lastResult = XRV_NOFILEOPEN;
	if (m_readOnly) return m_lastResult = XRV_READONLY;

	if (m_reading || m_writePos != m_fileSize)
	{
		m_reading = false;
		FSEEK_R(0);
	}
	fwrite(data, 1, length, m_handle);
	m_writePos = FTELL();
	m_fileSize = m_writePos;

	return (m_lastResult = XRV_OK);
}
Пример #21
0
	void bcLoadRawFile(const char* filename, unsigned char** data, unsigned int* size) {
		FILE* file;
		fopen_s(&file, filename, "rb");

		if (file) {

			FSEEK(file, 0, SEEK_END);
			*size = FTELL(file);
			FSEEK(file, 0, SEEK_SET);

			*data = new unsigned char[*size];
			FREAD(*data, *size, file);

			fclose(file);
		} else {
			LOG("Failed To Open File: %s\n", filename);
		}
	}
Пример #22
0
/*! \brief Write data to the end of the file.
	\details The function writes the given data to the file at the end. The
   current write
	position is also moved to the end of the file.
	\param bdata The byte data to append to the file
	\returns XRV_OK if the write was successful
*/
XsResultValue IoInterfaceFile::appendData(const XsByteArray& bdata)
{
	if (!m_handle) return m_lastResult = XRV_NOFILEOPEN;
	if (m_readOnly) return m_lastResult = XRV_READONLY;
	if (!bdata.size()) return m_lastResult = XRV_OK;

	if (m_reading || m_writePos != m_fileSize)
	{
		m_reading = false;
		FSEEK_R(0);  // lint !e534
	}
	size_t bytesWritten = fwrite(bdata.data(), 1, bdata.size(), m_handle);
	(void)bytesWritten;
	m_writePos = FTELL();
	m_fileSize = m_writePos;

	return (m_lastResult = XRV_OK);
}
Пример #23
0
	unsigned char* bcGetRawFile(const char* filename) {
		FILE* file;
		fopen_s(&file, filename, "rb");
		unsigned int size = 0;
		unsigned char* data;
		if (file) {

			FSEEK(file, 0, SEEK_END);
			size = FTELL(file);
			FSEEK(file, 0, SEEK_SET);

			data = new unsigned char[size];
			FREAD(data, size, file);

			fclose(file);
		} else {
			LOG("Failed To Open File: %s\n", filename);
		}

		return data;
	}
Пример #24
0
Errors Device_tell(DeviceHandle *deviceHandle, uint64 *offset)
{
  off_t n;

  assert(deviceHandle != NULL);
  assert(deviceHandle->file != NULL);
  assert(offset != NULL);

  n = FTELL(deviceHandle->file);
  if (n == (off_t)(-1))
  {
    return ERRORX_(IO_ERROR,errno,String_cString(deviceHandle->name));
  }
// NYI
//assert(sizeof(off_t)==8);
assert(n == (off_t)deviceHandle->index);

  (*offset) = deviceHandle->index;

  return ERROR_NONE;
}
Пример #25
0
int
f77nowreading (unit *x)
{
   XINT64 loc;
   FILE   *nfd;

   if (x->uacc == KEYED) goto read_mode;
   if (!(x->uwrt & WR_OP))
       return(0);
   if (x->uwrt == WR_OP) {
       /* write-only file */
      loc = FTELL (x->ufd);
      if (!loc) {
         /* obtain exclusive lock for special I/O operation */
         while (test_and_set( &io_lock, 1L ))
           ;
         nfd = freopen (x->ufnm, "r", x->ufd);
         io_lock = 0;
         if (!nfd)
	     return(1);
      } else {
         /* obtain exclusive lock for special I/O operation */
         while (test_and_set( &io_lock, 1L ))
           ;
         nfd = freopen (x->ufnm, "r+", x->ufd);
         io_lock = 0;
         if (!nfd)
            return (1);
	 x->uwrt = WR_READY;
	 FSEEK (x->ufd, loc, SEEK_SET);
      }
   }
   else
      fseek (x->ufd, 0L, SEEK_CUR);	/* dummy seek to reset FILE structure */
read_mode:
   x->uwrt &= ~WR_OP;
   return (0);
}
Пример #26
0
FskErr KplFileSetSize(KplFile fref, const KplInt64 *size) {
	FILEOFFSET	pos, oldpos;
	int ret;

	if (!fref) return kFskErrInvalidParameter;

	if (fref->thePermissions == kKplFilePermissionReadOnly)
		return kFskErrReadOnly;

	fref->flushBeforeRead = false;
	fref->flushBeforeWrite = false;

	pos = *size;
	oldpos = FTELL(fref->theFile);
	if (oldpos > pos)
		ret = FSEEK(fref->theFile, pos, SEEK_SET);

	ret = FTRUNCATE(fref->theFile, pos);
	if (-1 == ret)
		return errnoToFskErr(errno);

	return kFskErrNone;
}
Пример #27
0
int convert_slice(slice *slicei, int *thread_index) {

    char slicefile_svz[1024], slicesizefile_svz[1024];
    int fileversion, one, zero;
    char *slice_file;
    int version_local;
    char filetype[1024];
    char *shortlabel, *unit;
    char units[256];
    int ijkbar[6];
    uLong framesize;
    float *sliceframe_data=NULL;
    unsigned char *sliceframe_compressed=NULL, *sliceframe_uncompressed=NULL;
    unsigned char *sliceframe_compressed_rle=NULL, *sliceframe_uncompressed_rle=NULL;
    char cval[256];
    int sizebefore, sizeafter;
    int returncode;
    float minmax[2];
    float time_local;
    LINT data_loc;
    int percent_done;
    int percent_next=10;
    float valmin, valmax, denom;
    int chop_min, chop_max;
    uLongf ncompressed_zlib;
    int ncompressed_save;
#ifndef pp_THREAD
    int count=0;
#endif
    int ncol, nrow, idir;
    float time_max;
    int itime;
    LINT file_loc;

    FILE *SLICEFILE;
    FILE *slicestream,*slicesizestream;

#ifdef pp_THREAD
    if(GLOBcleanfiles==0) {
        int fileindex;

        fileindex = slicei + 1 - sliceinfo;
        sprintf(threadinfo[*thread_index].label,"sf %i",fileindex);
    }
#endif

    slice_file=slicei->file;
    version_local=slicei->version;

    fileversion = 1;
    one = 1;
    zero=0;

    // check if slice file is accessible

    strcpy(filetype,"");
    shortlabel=slicei->label.shortlabel;
    if(strlen(shortlabel)>0)strcat(filetype,shortlabel);
    trim(filetype);

    if(getfileinfo(slice_file,NULL,NULL)!=0) {
        fprintf(stderr,"*** Warning: The file %s does not exist\n",slice_file);
        return 0;
    }

    SLICEFILE=fopen(slice_file,"rb");
    if(SLICEFILE==NULL) {
        fprintf(stderr,"*** Warning: The file %s could not be opened\n",slice_file);
        return 0;
    }

    // set up slice compressed file

    if(GLOBdestdir!=NULL) {
        strcpy(slicefile_svz,GLOBdestdir);
        strcat(slicefile_svz,slicei->filebase);
    }
    else {
        strcpy(slicefile_svz,slicei->file);
    }
    {

        char *ext;
        int lensvz;

        lensvz = strlen(slicefile_svz);

        if(lensvz>4) {
            ext = slicefile_svz + lensvz - 4;
            if(strcmp(ext,".rle")==0) {
                slicefile_svz[lensvz-4]=0;
            }
            strcat(slicefile_svz,".svz");
        }
    }

    if(GLOBdestdir!=NULL) {
        strcpy(slicesizefile_svz,GLOBdestdir);
        strcat(slicesizefile_svz,slicei->filebase);
    }
    else {
        strcpy(slicesizefile_svz,slicei->file);
    }
    {

        char *ext;
        int lensvz;

        lensvz = strlen(slicesizefile_svz);

        if(lensvz>4) {
            ext = slicesizefile_svz + lensvz - 4;
            if(strcmp(ext,".rle")==0) {
                slicesizefile_svz[lensvz-4]=0;
            }
            strcat(slicesizefile_svz,".sz");
        }
    }

    if(GLOBcleanfiles==1) {
        slicestream=fopen(slicefile_svz,"rb");
        if(slicestream!=NULL) {
            fclose(slicestream);
            PRINTF("  Removing %s\n",slicefile_svz);
            UNLINK(slicefile_svz);
            LOCK_COMPRESS;
            GLOBfilesremoved++;
            UNLOCK_COMPRESS;
        }
        slicesizestream=fopen(slicesizefile_svz,"rb");
        if(slicesizestream!=NULL) {
            fclose(slicesizestream);
            PRINTF("  Removing %s\n",slicesizefile_svz);
            UNLINK(slicesizefile_svz);
            LOCK_COMPRESS;
            GLOBfilesremoved++;
            UNLOCK_COMPRESS;
        }
        return 0;
    }

    if(GLOBoverwrite_slice==0) {
        slicestream=fopen(slicefile_svz,"rb");
        if(slicestream!=NULL) {
            fclose(slicestream);
            fprintf(stderr,"*** Warning:  %s exists.\n",slicefile_svz);
            fprintf(stderr,"     Use the -f option to overwrite smokezip compressed files\n");
            return 0;
        }
    }

    slicestream=fopen(slicefile_svz,"wb");
    slicesizestream=fopen(slicesizefile_svz,"w");
    if(slicestream==NULL||slicesizestream==NULL) {
        if(slicestream==NULL) {
            fprintf(stderr,"*** Warning: The file %s could not be opened for writing\n",slicefile_svz);
        }
        if(slicesizestream==NULL) {
            fprintf(stderr,"  %s could not be opened for writing\n",slicesizefile_svz);
        }
        if(slicestream!=NULL)fclose(slicestream);
        if(slicesizestream!=NULL)fclose(slicesizestream);
        fclose(SLICEFILE);
        return 0;
    }

    // read and write slice header

    strcpy(units,"");
    unit=slicei->label.unit;
    if(strlen(unit)>0)strcat(units,unit);
    trim(units);
    sprintf(cval,"%f",slicei->valmin);
    trimzeros(cval);
#ifndef pp_THREAD
    if(GLOBcleanfiles==0) {
        PRINTF("Compressing %s (%s)\n",slice_file,filetype);
        PRINTF("  using min=%s %s",cval,units);
    }
#endif
    sprintf(cval,"%f",slicei->valmax);
    trimzeros(cval);
#ifndef pp_THREAD
    if(GLOBcleanfiles==0) {
        PRINTF(" max=%s %s\n",cval,units);
        PRINTF(" ");
    }
#endif
    valmin=slicei->valmin;
    valmax=slicei->valmax;
    denom = valmax-valmin;
    if(denom==0.0)denom=1.0;

    chop_min=0;
    chop_max=255;
    if(GLOBno_chop==0) {
        if(slicei->setchopvalmax==1) {
            chop_max = 255*(slicei->chopvalmax-valmin)/denom;
            if(chop_max<0)chop_max=0;
            if(chop_max>255)chop_max=255;
        }
        if(slicei->setchopvalmin==1) {
            chop_min = 255*(slicei->chopvalmin-valmin)/denom;
            if(chop_min<0)chop_min=0;
            if(chop_min>255)chop_min=255;
        }
    }


    fwrite(&one,4,1,slicestream);           // write out a 1 to determine "endianness" when file is read in later
    fwrite(&zero,4,1,slicestream);          // write out a zero now, then a one just before file is closed
    fwrite(&fileversion,4,1,slicestream);   // write out compressed fileversion in case file format changes later
    fwrite(&version_local,4,1,slicestream);       // fds slice file version
    sizeafter=16;

    //*** SLICE FILE FORMATS

    //*** FDS FORMAT (FORTRAN - each FORTRAN record has a 4 byte header and a 4 byte trailer surrounding the data)

    // 30 byte long label
    // 30 byte short label
    // 30 byte unit
    // i1,i2,j1,j2,k1,k2

    // for each time step:

    // time, compressed frame size
    // qq(1,nbuffer)              where nbuffer = (i2+1-i1)*(j2+1-j1)*(k2+1-k1)



    //*** ZLIB format (C - no extra bytes surrounding data)

    //*** header
    // endian
    // completion (0/1)
    // fileversion (compressed format)
    // version_local  (slicef version)
    // global min max (used to perform conversion)
    // i1,i2,j1,j2,k1,k2


    //*** frame
    // time, compressed frame size                        for each frame
    // compressed buffer


    //*** RLE format (FORTRAN)

    //*** header
    // endian
    // fileversion, slice version
    // global min max (used to perform conversion)
    // i1,i2,j1,j2,k1,k2


    //*** frame
    // time
    // compressed frame size                        for each frame
    // compressed buffer

    {
        int skip;

        skip = 3*(4+30+4);  // skip over 3 records each containing a 30 byte FORTRAN character string
        returncode=FSEEK(SLICEFILE,skip,SEEK_CUR);
        sizebefore=skip;
    }

    FORTSLICEREAD(ijkbar,6);
    sizebefore+=8+6*4;

    framesize =  (ijkbar[1]+1-ijkbar[0]);
    framesize *= (ijkbar[3]+1-ijkbar[2]);
    framesize *= (ijkbar[5]+1-ijkbar[4]);

    minmax[0]=slicei->valmin;
    minmax[1]=slicei->valmax;
    fwrite(minmax,4,2,slicestream);    // min max vals
    fwrite(ijkbar,4,6,slicestream);
    sizeafter+=(8+24);


    ncompressed_save=1.02*framesize+600;
    if(NewMemory((void **)&sliceframe_data,ncompressed_save*sizeof(float))==0)goto wrapup;
    if(NewMemory((void **)&sliceframe_compressed,ncompressed_save*sizeof(unsigned char))==0)goto wrapup;
    if(NewMemory((void **)&sliceframe_uncompressed,ncompressed_save*sizeof(unsigned char))==0)goto wrapup;

    fprintf(slicesizestream,"%i %i %i %i %i %i\n",ijkbar[0],ijkbar[1],ijkbar[2],ijkbar[3],ijkbar[4],ijkbar[5]);
    fprintf(slicesizestream,"%f %f\n",minmax[0],minmax[1]);

    idir=0;
    if(ijkbar[0]==ijkbar[1]) {
        idir=1;
        ncol = ijkbar[3] + 1 - ijkbar[2];
        nrow = ijkbar[5] + 1 - ijkbar[4];
    }
    else if(ijkbar[2]==ijkbar[3]) {
        idir=2;
        ncol = ijkbar[1] + 1 - ijkbar[0];
        nrow = ijkbar[5] + 1 - ijkbar[4];
    }
    else if(ijkbar[4]==ijkbar[5]) {
        idir=3;
        ncol = ijkbar[1] + 1 - ijkbar[0];
        nrow = ijkbar[3] + 1 - ijkbar[2];
    }
    if(idir==0) {
        idir=1;
        ncol = ijkbar[3] + 1 - ijkbar[2];
        nrow = ijkbar[5] + 1 - ijkbar[4];
    }


    {
        int ni, nj, nk;

        ni = ijkbar[1]+1-ijkbar[0];
        nj = ijkbar[3]+1-ijkbar[2];
        nk = ijkbar[5]+1-ijkbar[4];

        time_max=-1000000.0;
        itime=-1;
        for(;;) {
            int i;

            FORTSLICEREAD(&time_local,1);
            sizebefore+=12;
            if(returncode==0)break;
            FORTSLICEREAD(sliceframe_data,framesize);    //---------------
            if(returncode==0)break;

            sizebefore+=(8+framesize*4);
            if(time_local<time_max)continue;
            time_max=time_local;

#ifndef pp_THREAD
            count++;
#endif

            data_loc=FTELL(SLICEFILE);
            percent_done=100.0*(float)data_loc/(float)slicei->filesize;
#ifdef pp_THREAD
            threadinfo[*thread_index].stat=percent_done;
            if(percent_done>percent_next) {
                LOCK_PRINT;
                print_thread_stats();
                UNLOCK_PRINT;
                percent_next+=10;
            }
#else
            if(percent_done>percent_next) {
                PRINTF(" %i%s",percent_next,GLOBpp);
                FFLUSH();
                percent_next+=10;
            }
#endif
            for(i=0; i<framesize; i++) {
                int ival;
                int icol, jrow, index2;
                int ii,jj,kk;

                // val_in(i,j,k) = i + j*ni + k*ni*nj

                if(framesize<=ncol*nrow) { // only one slice plane

                    // i = jrow*ncol + icol;

                    icol = i%ncol;
                    jrow = i/ncol;

                    index2 = icol*nrow + jrow;
                }
                else {
                    ii = i%ni;
                    jj = (i/ni)%nj;
                    kk = i/(ni*nj);

                    index2 = ii*nj*nk + jj*nk + kk;
                }

                {
                    float val;

                    val = sliceframe_data[i];
                    if(val<valmin) {
                        ival=0;
                    }
                    else if(val>valmax) {
                        ival=255;
                    }
                    else {
                        ival = 1 + 253*(val-valmin)/denom;
                    }
                    if(ival<chop_min)ival=0;
                    if(ival>chop_max)ival=255;
                    sliceframe_uncompressed[index2] = ival;
                }
            }
            itime++;
            if(itime%GLOBslicezipstep!=0)continue;

            //int compress (Bytef *dest,   uLongf *destLen, const Bytef *source, uLong sourceLen);
            ncompressed_zlib=ncompressed_save;
            returncode=compress(sliceframe_compressed,&ncompressed_zlib,sliceframe_uncompressed,framesize);

            file_loc=FTELL(slicestream);
            fwrite(&time_local,4,1,slicestream);
            fwrite(&ncompressed_zlib,4,1,slicestream);
            fwrite(sliceframe_compressed,1,ncompressed_zlib,slicestream);
            sizeafter+=(8+ncompressed_zlib);
            fprintf(slicesizestream,"%f %i, %li\n",time_local,(int)ncompressed_zlib,(long)file_loc);
        }
        if(returncode!=0) {
            fprintf(stderr,"*** Error: compress returncode=%i\n",returncode);
        }
    }

wrapup:
#ifndef pp_THREAD
    PRINTF(" 100%s completed\n",GLOBpp);
#endif
    FREEMEMORY(sliceframe_data);
    FREEMEMORY(sliceframe_compressed);
    FREEMEMORY(sliceframe_uncompressed);
    FREEMEMORY(sliceframe_compressed_rle);
    FREEMEMORY(sliceframe_uncompressed_rle);

    fclose(SLICEFILE);
    FSEEK(slicestream,4,SEEK_SET);
    fwrite(&one,4,1,slicestream);  // write completion code
    fclose(slicestream);
    fclose(slicesizestream);

    {
        char before_label[256],after_label[256];

        getfilesizelabel(sizebefore,before_label);
        getfilesizelabel(sizeafter,after_label);
#ifdef pp_THREAD
        slicei->compressed=1;
        sprintf(slicei->summary,"compressed from %s to %s (%4.1f%s reduction)",before_label,after_label,(float)sizebefore/(float)sizeafter,GLOBx);
        threadinfo[*thread_index].stat=-1;
#else
        PRINTF("  records=%i, ",count);
        PRINTF("Sizes: original=%s, ",before_label);
        PRINTF("compressed=%s (%4.1f%s reduction)\n\n",after_label,(float)sizebefore/(float)sizeafter,GLOBx);
#endif
    }

    return 1;
}
Пример #28
0
int convert_volslice(slice *slicei, int *thread_index) {
    char slicefile_svz[1024];
    char *slice_file;
    char filetype[1024];
    char *shortlabel;
    int ijkbar[6];
    uLong framesize;
    float *sliceframe_data=NULL;
    int sizebefore, sizeafter;
    int returncode;
    LINT data_loc;
    int percent_done;
    int percent_next=10;
#ifndef pp_THREAD
    int count=0;
#endif
    FILE *SLICEFILE;
    FILE *slicestream;

#ifdef pp_THREAD
    if(GLOBcleanfiles==0) {
        int fileindex;

        fileindex = slicei + 1 - sliceinfo;
        sprintf(threadinfo[*thread_index].label,"vsf %i",fileindex);
    }
#endif

    slice_file=slicei->file;

    // check if slice file is accessible

    strcpy(filetype,"");
    shortlabel=slicei->label.shortlabel;
    if(strlen(shortlabel)>0)strcat(filetype,shortlabel);
    trim(filetype);

    if(getfileinfo(slice_file,NULL,NULL)!=0) {
        fprintf(stderr,"*** Warning: The file %s does not exist\n",slice_file);
        return 0;
    }

    SLICEFILE=fopen(slice_file,"rb");
    if(SLICEFILE==NULL) {
        fprintf(stderr,"*** Warning: The file %s could not be opened\n",slice_file);
        return 0;
    }

    // set up slice compressed file

    if(GLOBdestdir!=NULL) {
        strcpy(slicefile_svz,GLOBdestdir);
        strcat(slicefile_svz,slicei->filebase);
    }
    else {
        strcpy(slicefile_svz,slicei->file);
    }

    if(strlen(slicefile_svz)>4)strcat(slicefile_svz,".svv");

    if(GLOBcleanfiles==1) {
        slicestream=fopen(slicefile_svz,"rb");
        if(slicestream!=NULL) {
            fclose(slicestream);
            PRINTF("  Removing %s\n",slicefile_svz);
            UNLINK(slicefile_svz);
            LOCK_COMPRESS;
            GLOBfilesremoved++;
            UNLOCK_COMPRESS;
        }
        return 0;
    }

    if(GLOBoverwrite_slice==0) {
        slicestream=fopen(slicefile_svz,"rb");
        if(slicestream!=NULL) {
            fclose(slicestream);
            fprintf(stderr,"*** Warning: The file %s exists.\n",slicefile_svz);
            fprintf(stderr,"     Use the -f option to overwrite smokezip compressed files\n");
            return 0;
        }
    }

    slicestream=fopen(slicefile_svz,"wb");
    if(slicestream==NULL) {
        fprintf(stderr,"*** Warning: The file %s could not be opened for writing\n",slicefile_svz);
        return 0;
    }

    // read and write slice header

#ifndef pp_THREAD
    if(GLOBcleanfiles==0) {
        PRINTF("Compressing %s (%s)\n",slice_file,filetype);
    }
#endif


    {
        int skip;

        skip = 3*(4+30+4);  // skip over 3 records each containing a 30 byte FORTRAN character string
        returncode=FSEEK(SLICEFILE,skip,SEEK_CUR);
        sizebefore=skip;
    }

    FORTSLICEREAD(ijkbar,6);
    sizebefore+=4+6*4+4;
    sizeafter=0;

    {
        int one=1, version_local=0, completion=0;

        fwrite(&one,4,1,slicestream);
        fwrite(&version_local,4,1,slicestream);
        fwrite(&completion,4,1,slicestream);
    }


    {
        int ni, nj, nk;

        ni = ijkbar[1]+1-ijkbar[0];
        nj = ijkbar[3]+1-ijkbar[2];
        nk = ijkbar[5]+1-ijkbar[4];
        framesize = ni*nj*nk;
        NewMemory((void **)&sliceframe_data,framesize*sizeof(float));

        for(;;) {
            float vmin, vmax;
            float *valmin, *valmax;
            unsigned char *compressed_data_out;
            uLongf ncompressed_data_out;
            float time_local;

            FORTSLICEREAD(&time_local,1);
            if(returncode==0)break;
            CheckMemory;
            sizebefore+=12;

            FORTSLICEREAD(sliceframe_data,framesize);    //---------------
            if(returncode==0)break;
            CheckMemory;
            sizebefore+=(4+framesize*sizeof(float)+4);

            valmin=NULL;
            valmax=NULL;
            if(slicei->voltype==1) {
                vmin=0.0;
                valmin=&vmin;
            }
            else if(slicei->voltype==2) {
                vmin=20.0;
                valmin=&vmin;
                vmax=1400.0;
                valmax=&vmax;
            }
            else {
                ASSERT(0);
            }
            CheckMemory;
            compress_volsliceframe(sliceframe_data, framesize, time_local, valmin, valmax,
                                   &compressed_data_out, &ncompressed_data_out);
            CheckMemory;
            sizeafter+=ncompressed_data_out;
            if(ncompressed_data_out>0) {
                fwrite(compressed_data_out,1,ncompressed_data_out,slicestream);
            }
            CheckMemory;
            FREEMEMORY(compressed_data_out);

#ifndef pp_THREAD
            count++;
#endif

            data_loc=FTELL(SLICEFILE);
            percent_done=100.0*(float)data_loc/(float)slicei->filesize;
#ifdef pp_THREAD
            threadinfo[*thread_index].stat=percent_done;
            if(percent_done>percent_next) {
                LOCK_PRINT;
                print_thread_stats();
                UNLOCK_PRINT;
                percent_next+=10;
            }
#else
            if(percent_done>percent_next) {
                PRINTF(" %i%s",percent_next,GLOBpp);
                FFLUSH();
                percent_next+=10;
            }
#endif

        }
        if(returncode!=0) {
            fprintf(stderr,"*** Error: compress returncode=%i\n",returncode);
        }
        FREEMEMORY(sliceframe_data);
    }

#ifndef pp_THREAD
    PRINTF(" 100%s completed\n",GLOBpp);
#endif

    {
        int completion=1;

        FSEEK(slicestream,4,SEEK_SET);
        fwrite(&completion,4,1,slicestream);
    }
    fclose(SLICEFILE);
    fclose(slicestream);

    {
        char before_label[256],after_label[256];

        getfilesizelabel(sizebefore,before_label);
        getfilesizelabel(sizeafter,after_label);
#ifdef pp_THREAD
        slicei->vol_compressed=1;
        sprintf(slicei->volsummary,"compressed from %s to %s (%4.1f%s reduction)",before_label,after_label,(float)sizebefore/(float)sizeafter,GLOBx);
        threadinfo[*thread_index].stat=-1;
#else
        PRINTF("  records=%i, ",count);
        PRINTF("Sizes: original=%s, ",before_label);
        PRINTF("compressed=%s (%4.1f%s reduction)\n\n",after_label,(float)sizebefore/(float)sizeafter,GLOBx);
#endif
    }

    return 1;

}
Пример #29
0
static ftnint
__f77_f_back_com (alist *a, int lock) 

{
   unit           *ftnunit;
   int             n, i;
   ftnll            x, y;
   char            buf[512];

   if ((ftnunit = find_luno (a->aunit)) == NULL)
      err(a->aerr, 114, "backspace");
   while (lock && test_and_set( &ftnunit->lock_unit, 1L ))
       ;
   if (ftnunit->uacc == APPEND || ftnunit->uacc == KEYED)
      errret(a->aerr, 165, "backspace");
   if (ftnunit->useek == 0 || ftnunit->url == 1)
      errret(a->aerr, 106, "backspace");
   if (ftnunit->uend == 1) {
      ftnunit->uend = 0;
      ftnunit->lock_unit = 0;
      return (0);
   }
   if (ftnunit->uwrt & WR_OP) {
#ifdef I90
      /* If in Fortran-90 nonadvancing mode, write endfile record (\n only). */
      if (ftnunit->f90sw == 1 && ftnunit->f90nadv == 1 ) {
	  putc ('\n', ftnunit->ufd);
	  ftnunit->f90nadv = 0;
      }
#endif
      /* Just completed a write operation, a backspace would force
      the truncation of the file at the current position.
      */
      (void) t_runc (ftnunit, a->aerr);
      /* make sure it gets switched back to reading mode so the
      file won't get truncated again if it gets backspace/rewind again
      */
      if (f77nowreading(ftnunit))
	 errret(a->aerr, 106, "backspace");
   }
   /* Backspace a direct unformatted file. */

   if ((ftnunit->uacc == DIRECT) && (ftnunit->ufmt == 0)) {
      if (ftnunit->uirec != 0)
	 ftnunit->uirec--;
      ftnunit->lock_unit = 0;
      return (0);
   }
   if (ftnunit->ufmt != 1) {
      if (ftnunit->uerror)
	 unf_position (ftnunit->ufd, ftnunit);
      if (fseek (ftnunit->ufd, -(long) sizeof (int), 1)) {
	  fseek(ftnunit->ufd, 0L, 0);
          ftnunit->lock_unit = 0;
	  return(0);
      }
      /* NEED TO CHANGE HERE DLAI */
      (void) fread ((char *) &n, sizeof (int), 1, ftnunit->ufd);
      (void) fseek (ftnunit->ufd, (long) (-n - 2 * sizeof (int)), 1);
      ftnunit->lock_unit = 0;
      return (0);
   }

   y = x = FTELL (ftnunit->ufd) - 1;	/* skip the last CR */

   /* If already at the beginning of file, ignore the backspace */

   if (x < 0) {
      ftnunit->lock_unit = 0;
      return (0);
   }

#ifdef I90
   /* Make sure these variables are zeroed out to allow record to be reread. */
   ftnunit->f77recpos = 0;
   ftnunit->f77recend = 0;
#endif

   for (;;) {
      if (x < sizeof (buf))
	 x = 0;
      else
	 x -= sizeof (buf);
      (void) FSEEK (ftnunit->ufd, x, 0);
      /* n should be ll for 64 bit records */
      n = (int) fread (buf, 1, (int) (y - x), ftnunit->ufd);
      for (i = n - 1; i >= 0; i--) {
	 if (buf[i] != '\n')
	    continue;
	 (void) fseek (ftnunit->ufd, (long) (i + 1 - n), 1);
         ftnunit->lock_unit = 0;
	 return (0);
      }
      if (x == 0) {
	 (void) fseek (ftnunit->ufd, 0L, 0);
         ftnunit->lock_unit = 0;
	 return (0);
      } else if (n <= 0)
	 errret (a->aerr, (EOF), "backspace")
	    (void) FSEEK (ftnunit->ufd, x, 0);
      y = x;
   }
}
Пример #30
0
static int
f_rew_com (alist *a, int lock)
{
   unit           *ftnunit;
  
   if ((ftnunit = find_luno (a->aunit)) == NULL)
      return(0);
   while (lock && test_and_set( &ftnunit->lock_unit, 1L ))
       ;

   if (ftnunit->uacc == KEYED)
      errret(a->aerr, 164, "rewind");

   if (ftnunit->uconn <= 0) {
      ftnunit->lock_unit = 0;
      return (0);
   }

   if (!ftnunit->useek && !ftnunit->uistty)
      errret(a->aerr, 106, "rewind");
   ftnunit->uend = 0;

   /* Need to reset the associate variable to 1 if exists */
   if (ftnunit->uassocv)
      set_var (ftnunit->uassocv, ftnunit->umask, ASSOCV, (ftnll) 1);

   /* Rewind of a direct unformatted file. */

   if ((ftnunit->uacc == DIRECT) && (ftnunit->ufmt == 0)) {
      if (-1 == lseek ((int) ftnunit->ufd, 0, SEEK_SET)) {
	 errret(a->aerr, 106, "rewind");
      }
      /* need to change the internal buffer position in fio_direct_io as well */
      _fio_set_seek((int) ftnunit->ufd,  (ftnll) 0, 0);
      ftnunit->uirec = 0;
      ftnunit->lock_unit = 0;
      return (1);
   }

#ifdef I90
   /* Make sure these variables are zeroed out to allow record to be reread. */
   ftnunit->f77recpos = 0;
   ftnunit->f77recend = 0;
#endif

   if (f77vms_flag_[VMS_EF]) {	/* rewind to the last endfile record
				 * or beginning of file */
      char            buf[513];
      XINT64             y, x;
      int	 i, n;
      char            ch;

      /*  If last operation was a WRITE, truncate the file and then make
      sure that the file mode is switched to READ so the the next 
      REWIND/BACKSPACE won't truncate the file again
      */
      if (ftnunit->uwrt & WR_OP) {
#ifdef I90
	 /* If in Fortran-90 nonadvancing mode, write endfile record (\n only). */
	 if (ftnunit->f90sw == 1 && ftnunit->f90nadv == 1 ) {
	     putc ('\n', ftnunit->ufd);
	     ftnunit->f90nadv = 0;
	 }
#endif
	 (void) t_runc (ftnunit, a->aerr);
	 /* If the file is in write-only mode make sure that it is readable */
	 if (f77nowreading(ftnunit))
	    errret(a->aerr, 106, "rewind");
      }
      if (ftnunit->ufmt != 1) {
	 if (ftell (ftnunit->ufd) == 0) {
            ftnunit->lock_unit = 0;
	    return (0);		/* already at beginning of file */
	 }
	 if (fseek (ftnunit->ufd, (long) (-sizeof (int)), 1) < 0)
	    errret(a->aerr, 106, "rewind");
	 for (i = 0;; i++) {
	    (void) fread ((char *) &n, sizeof (int), 1, ftnunit->ufd);
	    if (n != 1 || i == 0) {
	       if (fseek (ftnunit->ufd, (long) (-n - 3 * sizeof (int)), 1)) {
		  rewind (ftnunit->ufd);
                  ftnunit->lock_unit = 0;
		  return (0);
	       }
	    } else {
	       if (fseek (ftnunit->ufd, -(sizeof (int) + 1), 1)) {
		  rewind (ftnunit->ufd);
                  ftnunit->lock_unit = 0;
		  return (0);
	       }
	       (void) fread ((char *) &ch, 1, 1, ftnunit->ufd);
	       if (ch == '\032') {
		  fseek (ftnunit->ufd, sizeof (int), 1);
                  ftnunit->lock_unit = 0;
		  return (0);
	       }
	       fseek (ftnunit->ufd, -(2 * sizeof (int) + 1), 1);
	    }
	 }
      }
      y = x = FTELL (ftnunit->ufd) - 2;	/* skip the last endfile
					 * record */
      if (y < 0) {
	  (void) fseek(ftnunit->ufd, 0L, 0);
          ftnunit->lock_unit = 0;
	  return(0);
      }
      ch = '\0';
      for (;;) {
	 if (x < sizeof (buf) - 1)
	    x = 0;
	 else
	    x -= sizeof (buf) - 1;
	 (void) FSEEK (ftnunit->ufd, x, 0);
	 n = (int) fread (buf, 1, (int) (y - x), ftnunit->ufd);
	 buf[n] = ch;
	 for (i = n - 1; i >= 1; i--) {
	    if (buf[i] != '\032' || buf[i + 1] != '\n')
	       continue;
	    (void) fseek (ftnunit->ufd, (long) (i + 2 - n), 1);
            ftnunit->lock_unit = 0;
	    return (0);
	 }
	 if (x == 0) {
	    (void) fseek (ftnunit->ufd, 0L, 0);
            ftnunit->lock_unit = 0;
	    return (0);
	 }
	 y = x;
	 ch = buf[0];
      }
   }
      /*  If last operation was a WRITE, truncate the file and then make
      sure that the file mode is switched to READ so the the next 
      REWIND/BACKSPACE won't truncate the file again
      */
   if (ftnunit->uwrt & WR_OP) {
#ifdef I90
      /* If in Fortran-90 nonadvancing mode, write endfile record (\n only). */
      if (ftnunit->f90sw == 1 && ftnunit->f90nadv == 1 ) {
	  putc ('\n', ftnunit->ufd);
	  ftnunit->f90nadv = 0;
      }
#endif
      (void) t_runc (ftnunit, a->aerr);
      /* If the file is in write-only mode make sure that it is readable */
      if (f77nowreading(ftnunit))
	 errret(a->aerr, 106, "backspace");
   }
   rewind (ftnunit->ufd);
   ftnunit->lock_unit = 0;
   return (0);
}