/* This file is part of Lcrzo.
*/

/*-------------------------------------------------------------*/
int lcrzo_file_flush(lcrzo_file *pfile)
{ int ret;

  if (pfile==NULL) return(LCRZO_ERR_OK);

  if (pfile->openforreading)
  { if (pfile->fd==0) /* flush stdin */
#if defined LCRZODEF_SYSTEM_Unix
    { int old_fc, new_fc, c;

      /*le getc n'est pas bloquant*/
      if ( (old_fc=fcntl(0, F_GETFL, 0)) == -1 )
      { return(LCRZO_ERR_FUFCNTL);
      }
      new_fc = old_fc | O_NONBLOCK;
      if ( fcntl(0, F_SETFL, new_fc) == -1 )
      { return(LCRZO_ERR_FUFCNTL);
      }
      do { c = getchar(); } while ( c!=EOF );
      /*redefinitions des caracteristiques*/
      if ( fcntl(0, F_SETFL, old_fc) == -1 )
      { return(LCRZO_ERR_FUFCNTL); 
      }
      errno=0;
    }
#elif defined LCRZODEF_SYSTEM_Windows
  { while (_kbhit()) _getch();
	lcrzo_err_purge();
  }
#else
 #error "Unknown value for LCRZODEF_SYSTEM"
#endif
    else
    { /* do not read any more data : should we do it ? */
    }
    /* flush storead data */
    if (pfile->storeddata==NULL && pfile->storeddatasize) return(LCRZO_ERR_PANULLPTRSIZE);
    if (pfile->storeddatasize)
    { lcrzo_er(lcrzo_data_free(pfile->storeddata));
      pfile->storeddata=NULL;
      pfile->storeddatasize=0;
    }
  }

  if (pfile->openforwriting)
  { if (pfile->fd==0)
    { /* flush stdin has no sense */
    }
    else if (pfile->fd==1)
    { fflush(stdout);
    }
    else if (pfile->fd==2)
    { fflush(stderr);
    }
    else
    {
#if defined LCRZODEF_SYSTEM_Unix
      ret=fsync(pfile->fd);
#elif defined LCRZODEF_SYSTEM_Windows
      ret=_commit(pfile->fd);
#else
 #error "Unknown value for LCRZODEF_SYSTEM"
#endif
      if (ret<0) return(LCRZO_ERR_FUFSYNC);
    }
  }
  return(LCRZO_ERR_OK);
}

