Example #1
0
File: ga5.c Project: POFK/Tide
/*==============================*/
int main(void)  {
    float input, dx, dy;
    float out1, out2;
    int   i, j, k;

    char pathx[80] = {"../../tides05/0.000wdengdx1.25.bin"};
    char pathy[80] = {"../../tides05/0.000wdengdy1.25.bin"};

    FILE *DENX = fopen(pathx, "rb");
    FILE *DENY = fopen(pathy, "rb");

    FILE *GAM1 = fopen("../../tides05/0.000wgam1gd1.25.bin", "wb");
    FILE *GAM2 = fopen("../../tides05/0.000wgam2gd1.25.bin", "wb");

    printf("Reading&Outputing...\n");
    for(k = 0; k < nc; k++)  {
        for(j = 0; j < nc; j++)  {
            for(i = 0; i < nc; i++)  {
                fread(&dx,    4, 1, DENX);
                fread(&dy,    4, 1, DENY);
                out1 = dx*dx - dy*dy;
                out2 = 2.*dx*dy;
                fwrite(&out1, 4, 1, GAM1);
                fwrite(&out2, 4, 1, GAM2);
            }
        }
    }
    printf("End...\n");

    return 0;
}
Example #2
0
int main(int argc, char **argv)
{
    if ( argc<4 ) {
        printf("Usage: logocnv startlogo stoplogo outfile\n");
        exit(1);
    }
    LVImageSourceRef startimg = LVCreateFileCopyImageSource( lString16(argv[1]) );
    if ( startimg.isNull() ) {
        printf("Cannot open image from file %s\n", argv[1]);
        exit(1);
    }
    printf("Start image: %s %d x %d\n", argv[1], startimg->GetWidth(), startimg->GetHeight());
    LVGrayDrawBuf buf1( 600, 800, 3 );
    buf1.Draw(startimg, 0, 0, 600, 800, true);
    LVImageSourceRef stopimg = LVCreateFileCopyImageSource( lString16(argv[2]) );
    if ( stopimg.isNull() ) {
        printf("Cannot open image from file %s\n", argv[2]);
        exit(1);
    }
    printf("Stop image: %s %d x %d\n", argv[1], startimg->GetWidth(), startimg->GetHeight());
    LVGrayDrawBuf buf2( 600, 800, 3 );
    buf2.Draw(stopimg, 0, 0, 600, 800, true);

    FILE * out = fopen( argv[3], "wb" );
    if ( !out ) {
        printf("Cannot create output file %s", argv[3]);
        exit(1);
    }
    int written = 0;
    written += fwrite(buf1.GetScanLine(0), 1, buf1.GetRowSize()*buf1.GetHeight(), out );
    written += fwrite(buf2.GetScanLine(0), 1, buf2.GetRowSize()*buf2.GetHeight(), out );
    fclose(out);
    printf("%d bytes written to file %s\n", written, argv[3]);
}
Example #3
0
/**
 * Save service state information to the state file
 */
void State_save() {

  int l= 0;
  Service_T s;
  State_T state;
  FILE *S= NULL;
  
  if(! (S= open_state("w")))
      return;

  l= Util_getNumberOfServices();
  
  if(fwrite(&l, 1, sizeof (int), S) != sizeof(int)) {
    LogError("%s: Unable to save monit state information to '%s'\n",
	prog, Run.statefile);
    goto error;
  }
  
  for(s= servicelist; s; s= s->next) {
    clone_state(s, &state);
    if(fwrite(&state, 1, sizeof(State_T), S) != sizeof(State_T)) {
      LogError("%s: An error occured when saving monit state information "
	  "for the service %s\n", prog, s->name);
      goto error;
    }
  }
  
  error:
  close_state(S);
}
Example #4
0
void ObjectFactory::dumpObjectPack() const {
    bool dump_pack = GetOptionValue<bool>(OBJECT_PACK_DUMP);
    if (!dump_pack) return;

    String pack_filename = GetOptionValue<String>(OBJECT_PACK);
    assert(!pack_filename.empty());

    FILE* pack_file = fopen(pack_filename.c_str(), "wb");
    if (pack_file == NULL) {
        SILOG(objectfactory,error,"Couldn't open object pack file, not dumping any objects.");
        assert(false);
        return;
    }

    uint64 pack_id_gen = 1;
    for(ObjectInputsMap::const_iterator it = mInputs.begin(); it != mInputs.end(); it++) {
        uint64 pack_objid = pack_id_gen++;
        ObjectInputs* inputs = it->second;

        fwrite( &pack_objid, sizeof(uint64), 1, pack_file );
        Vector3f startpos = inputs->motion->initial().position();
        float64 x = startpos.x, y = startpos.y, z = startpos.z;
        fwrite( &(x), sizeof(x), 1, pack_file );
        fwrite( &(y), sizeof(x), 1, pack_file );
        fwrite( &(z), sizeof(x), 1, pack_file );
        float64 rad = inputs->bounds.radius();
        fwrite( &rad, sizeof(rad), 1, pack_file );
    }

    fclose(pack_file);
}
Example #5
0
int main(void)
{
	FILE *fichero_origen = fopen("datos.txt", "rt");
	int n1, n2, res;
	char signo;
	FILE *fichero_destino = fopen("resultados.dat", "wb");
	
	/*Leemos del fichero de texto */
	while(fscanf(fichero_origen, "%i %c %i",&n1, &signo, &n2) != EOF)
	{
		/*Realizamos y guardamos el resultado de la operacion adecuada en funcion del signo*/
		if (signo=='+')
		{
			res = n1 + n2;
			fwrite(&res, sizeof(res), 1, fichero_destino);
		}
		else if (signo == '-')
		{
			res = n1 - n2;
			fwrite(&res, sizeof(res), 1, fichero_destino);
		}
		else
		{
			printf("Caracter de signo desconocido. No se guardara en fichero binario.\n");
		}
	}
	
	fclose(fichero_destino);
	fclose(fichero_origen);

	return 0;
}
Example #6
0
void _flush_wcache(struct cached_io *cio, char *extra, int64_t extra_size) {
  FILE *io;
  struct stat out_stats;
  if (cio->wcache_pos || extra_size) {
    if (cio->append) io = check_fopen(cio->filename, "a");
    else {
      io = fopen(cio->filename, "r+");
      if (!io) io = check_fopen(cio->filename, "w");
      fseeko(io, cio->wpos, SEEK_SET);
    }
    //if (cio->do_locks) flock(fileno(io), LOCK_EX);
    
    if (cio->append) fseek(io, 0, SEEK_END);
    if (cio->header) {
      fstat(fileno(io), &out_stats);
      if (!out_stats.st_size)
	fwrite(cio->header, 1, strlen(cio->header), io);
    }
    if (cio->wcache_pos) fwrite(cio->wcache, 1, cio->wcache_pos, io);
    if (extra) fwrite(extra, 1, extra_size, io);
    fflush(io);
    cio->wpos += cio->wcache_pos + extra_size;
    //if (cio->do_locks) flock(fileno(io), LOCK_UN);
    fclose(io);
    cio->wcache_pos = 0;
  }
}
static
void fft_file_real(FILE * fin, FILE * fout, int nfft, int isinverse)
{
    kiss_fftr_cfg st;
    kiss_fft_scalar * rbuf;
    kiss_fft_cpx * cbuf;

    rbuf = (kiss_fft_scalar*)malloc(sizeof(kiss_fft_scalar) * nfft);
    cbuf = (kiss_fft_cpx*)malloc(sizeof(kiss_fft_cpx) * (nfft / 2 + 1));
    st = kiss_fftr_alloc(nfft , isinverse , 0, 0);

    if (isinverse == 0) {
        while (fread(rbuf , sizeof(kiss_fft_scalar) * nfft , 1, fin) > 0) {
            kiss_fftr(st , rbuf , cbuf);
            fwrite(cbuf , sizeof(kiss_fft_cpx) , (nfft / 2 + 1) , fout);
        }
    } else {
        while (fread(cbuf , sizeof(kiss_fft_cpx) * (nfft / 2 + 1) , 1, fin) > 0) {
            kiss_fftri(st , cbuf , rbuf);
            fwrite(rbuf , sizeof(kiss_fft_scalar) , nfft , fout);
        }
    }
    free(st);
    free(rbuf);
    free(cbuf);
}
Example #8
0
void output_saveResults(Project* project, double reportTime)
//
//  Input:   reportTime = elapsed simulation time (millisec)
//  Output:  none
//  Purpose: writes computed results for current report time to binary file.
//
{
    int i;
    DateTime reportDate = getDateTime(project,reportTime);
    REAL8 date;

    if ( reportDate < project->ReportStart ) return;
    for (i=0; i<MAX_SYS_RESULTS; i++) project->SysResults[i] = 0.0f;
    date = reportDate;
    fwrite(&date, sizeof(REAL8), 1, project->Fout.file);
    if (project->Nobjects[SUBCATCH] > 0)
        output_saveSubcatchResults(project,reportTime, project->Fout.file);
    if (project->Nobjects[NODE] > 0)
        output_saveNodeResults(project,reportTime, project->Fout.file);
    if (project->Nobjects[LINK] > 0)
        output_saveLinkResults(project,reportTime, project->Fout.file);
    fwrite(project->SysResults, sizeof(REAL4), MAX_SYS_RESULTS, project->Fout.file);
    if ( project->Foutflows.mode == SAVE_FILE && !project->IgnoreRouting ) 
        iface_saveOutletResults(project,reportDate, project->Foutflows.file);
    project->Nperiods++;
}
Example #9
0
size_t sim_fwrite (void *bptr, size_t size, size_t count, FILE *fptr)
{
size_t c, nelem, nbuf, lcnt, total;
int32 i;
unsigned char *sptr;
unsigned char *sim_flip;

if ((size == 0) || (count == 0))                        /* check arguments */
    return 0;
if (sim_end || (size == sizeof (char)))                 /* le or byte? */
    return fwrite (bptr, size, count, fptr);            /* done */
sim_flip = (unsigned char *)malloc(FLIP_SIZE);
if (!sim_flip)
    return 0;
nelem = FLIP_SIZE / size;                               /* elements in buffer */
nbuf = count / nelem;                                   /* number buffers */
lcnt = count % nelem;                                   /* count in last buf */
if (lcnt) nbuf = nbuf + 1;
else lcnt = nelem;
total = 0;
sptr = (unsigned char *) bptr;                          /* init input ptr */
for (i = (int32)nbuf; i > 0; i--) {                     /* loop on buffers */
    c = (i == 1)? lcnt: nelem;
    sim_buf_copy_swapped (sim_flip, sptr, size, c);
    sptr = sptr + size * count;
    c = fwrite (sim_flip, size, c, fptr);
    if (c == 0) {
        free(sim_flip);
        return total;
        }
    total = total + c;
    }
free(sim_flip);
return total;
}
main(){
    
    FILE *file;
    char linha[256];
    
    file = fopen("dados.dat", "rb+");
    
    if(file == NULL)
        file = fopen("dados.dat", "wb+");
        
    getchar();
    fseek(file, 0, SEEK_SET);
    fwrite("primeiroBloco", 256, 1, file);
    fseek(file, 0, SEEK_SET);
    fread(linha, 256, 1, file);
    printf("\n\n%s\n\n", linha);
    
    getchar();
    fseek(file, 0, SEEK_SET);
    fwrite("segundoBloco", 256, 1, file);
    fseek(file, 0, SEEK_SET);
    fread(linha, 256, 1, file);
    printf("\n\n%s\n\n", linha);
    
    getchar();
}
Example #11
0
int main()
{
    // TODO
    int i=0,j,prev=0;
    char title[8];
    FILE* file = fopen("card.raw", "r");
    uint8_t buffer[512];
    while(1)
    {
        if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] == 0xe0 || buffer[3] == 0xe1))
        {
             prev=1;
             sprintf(title,"%03d.jpg",i);
             FILE* image = fopen(title,"a");
             fwrite(buffer,512,1,image);
             fclose(image);
             i++;
        }
        else if(prev==1)
        {
            FILE* image = fopen(title,"a");
            fwrite(buffer,512,1,image);
            fclose(image);
        }
        j=fread(buffer,512,1,file);
        if(j==0)
        {
            break;
        }
    }
    return 0;
}
Example #12
0
int writebook(int editadd)
{
if (editadd==1) // Request to write New records
	{ fseek(fp,0,SEEK_END); // Moves 0 byte from end
	  if(fwrite(&book,rec_size,1,fp)) {fflush(fp);return 1;}
	  else return 0;
	}
if (editadd==2) //Request to write Edited records
	{
	  fseek(fp,-rec_size,SEEK_CUR); //File pointer shifted to the Start of Found Record
	  if(fwrite(&tmp,rec_size,1,fp))
	  {fflush(fp);
	  return 2;}
	  else return 0;
	}
return 0; //Zero return of this function won't interfere with our Output.
/*
strset(book.name,' ');
strset(book.author,' ');
strset(book.pub,' ');
strset(book.edition,' ');
strset(book.isbn,' ');

strset(book.lc,' ');
strset(book.accno,' ');
strset(book.bookno,' ');

strset(book.issue_to,' ');
strset(book.issue_date,' ');
strset(book.due_date,' ');
*/
}
Example #13
0
static void print_tb(const SaHpiTextBufferT * tb)
{
        size_t i;

        switch (tb->DataType) {
                case SAHPI_TL_TYPE_UNICODE:
                        printf("UNICODE: Unsupported output");
                        return;
                case SAHPI_TL_TYPE_BCDPLUS:
                        printf("BCD+ : ");
                        fwrite(&tb->Data[0], tb->DataLength, 1, stdout);
                        return;
                case SAHPI_TL_TYPE_ASCII6:
                        printf("ASCII6 : ");
                        fwrite(&tb->Data[0], tb->DataLength, 1, stdout);
                        return;
                case SAHPI_TL_TYPE_TEXT:
                        printf("TEXT : ");
                        fwrite(&tb->Data[0], tb->DataLength, 1, stdout);
                        return;
                case SAHPI_TL_TYPE_BINARY:
                        printf("BIN :");
                        for (i = 0; i < tb->DataLength; ++i) {
                                printf(" %02X", tb->Data[i]);
                        }
                        return;
                default:
                        printf("???    : ");
                        return;
        }
}
Example #14
0
void CIniFile::saveTo(const char *pszFile)
{
    assert(NULL != pszFile);

    FILE *pFile = NULL;
    std::string strTmp;
    std::list<stIniNode>::iterator itNodeInfo;
    std::list<stIniKey>::iterator itKeyInfo;    

    pFile = fopen(pszFile, "w");
    if (NULL == pFile)
    {
        return;
    }

    for (itNodeInfo = m_lstNodeInfo.begin(); m_lstNodeInfo.end() != itNodeInfo; itNodeInfo++)
    {
        strTmp = std::string("[") + itNodeInfo->strNode + std::string("]\n");
        fwrite(strTmp.c_str(), 1, strTmp.size(), pFile);

        for (itKeyInfo = itNodeInfo->lstKey.begin(); itNodeInfo->lstKey.end() != itKeyInfo;
            itKeyInfo++)
        {
            strTmp = itKeyInfo->strKey + std::string(" = ") + itKeyInfo->strValue + std::string("\n");
            fwrite(strTmp.c_str(), 1, strTmp.size(), pFile);
        }
    }

    fclose(pFile);

    return;
}
Example #15
0
void WriteDataToReportFile(char *lpLogFileFilename, tSmbNtlmAuthResponse* NtlmAuthResponse, char *SourceIpAddress,unsigned char *challenge)
{
	char buffer[1024];
	char tmp[256];
	FILE *LogFile=NULL;
	char UserName[256];
	char Domain[256];
	char Workstation[256];
	unsigned char *p;
	int i;

		
	LogFile=fopen(lpLogFileFilename,"a+");
	strcpy(tmp,"#SOURCEIPADDRESS:DOMAIN:WORKSTATION:USERNAME:challenge:LMHASH:NTLMHASH\n");
	fwrite(tmp,strlen(tmp),1,LogFile);
	
	GetNTLMPacketInfo(NtlmAuthResponse,(char*)&UserName, (char*)&Domain, (char*)&Workstation,0);
	sprintf(buffer,"%s:%s:%s:%s:",SourceIpAddress,Domain,Workstation,UserName);
		//Challenge:
		sprintf(tmp,"%2.2x%2.2x%2.2x%2.2x%2.2x%2.2x%2.2x%2.2x:",challenge[0],challenge[1],challenge[2],challenge[3],challenge[4],challenge[5],challenge[6],challenge[7]);
		strcat(buffer,tmp);
		//LM HASH		
		p=(unsigned char *)NtlmAuthResponse + NtlmAuthResponse->lmResponse.offset;
		//printf("LM\n");
		//DumpMem(p,24);
		for(i=0;i<24;i++) {sprintf(tmp,"%2.2x",p[i]); strcat(buffer,tmp); }
		strcat(buffer,":");
		//NT HASH		
		p=(unsigned char *)NtlmAuthResponse + NtlmAuthResponse->ntResponse.offset;
		for(i=0;i<24;i++) {sprintf(tmp,"%2.2x",p[i]); strcat(buffer,tmp); }
		fwrite(buffer,strlen(buffer),1,LogFile);
		fclose(LogFile);


}
Example #16
0
/*--------------------------------------------------------------------------*/
void write_sac (char *fname, float *sig, SAC_HD *SHD)
/*--------------------------------------------------------------------------*/
{
  FILE *fsac;
  int i;
  if((fsac = fopen(fname, "wb"))==NULL) {
    printf("could not open sac file to write\n");
    exit(1);
  }

  if ( !SHD ) {
    SHD = &SAC_HEADER;
  }

  SHD->iftype = (int)ITIME;
  SHD->leven = (int)TRUE;
  SHD->lovrok = (int)TRUE;
  SHD->internal4 = 6L;
  SHD->depmin = sig[0];
  SHD->depmax = sig[0];

  for ( i = 0; i < SHD->npts ; i++ ) {
    if ( SHD->depmin > sig[i] ) {
      SHD->depmin = sig[i];
    }
    if ( SHD->depmax < sig[i] ) {
      SHD->depmax = sig[i];
    }
   }

  fwrite(SHD,sizeof(SAC_HD),1,fsac);
  fwrite(sig,sizeof(float),(int)(SHD->npts),fsac);

  fclose (fsac);
}
Example #17
0
void SaveBitmap(char *fileName,unsigned char *pBuf, int w, int h)
{
     if(!fileName || !pBuf) return;
     FILE *fp = NULL;
     fp = fopen(fileName,"wb");
     if(fp != NULL) 
     {
        BITMAPINFO bmpinfo;
        // bitmapinfoheader 
        BITMAPFILEHEADER  bmpfileheader;
        ZeroMemory(&bmpinfo, sizeof(BITMAPINFO));
        bmpinfo.bmiHeader.biSize=sizeof(BITMAPFILEHEADER);

            
        bmpinfo.bmiHeader.biHeight = -h;
        bmpinfo.bmiHeader.biWidth  = w;
        bmpinfo.bmiHeader.biSizeImage = abs(bmpinfo.bmiHeader.biHeight) * bmpinfo.bmiHeader.biWidth * 4;

        bmpinfo.bmiHeader.biCompression = BI_RGB;
        bmpinfo.bmiHeader.biPlanes = 1;
        bmpinfo.bmiHeader.biBitCount = 32;

        bmpfileheader.bfReserved1=0;
        bmpfileheader.bfReserved2=0;
        bmpfileheader.bfSize=sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFO)+bmpinfo.bmiHeader.biSizeImage;
        bmpfileheader.bfType = MakeIntelWord('M','B');
        bmpfileheader.bfOffBits=sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFO);


        fwrite(&bmpfileheader,sizeof(BITMAPFILEHEADER),1,fp);
        fwrite(&bmpinfo.bmiHeader,sizeof(BITMAPINFOHEADER),1,fp);
        fwrite(pBuf, bmpinfo.bmiHeader.biSizeImage, 1, fp);
        fclose(fp);
     }
}
Example #18
0
void Arecord_remove(FILE *fp, char *hostname)
{
	char *tmpfname = tempnam(NULL, "A_DB_");
	FILE *tmpf = fopen(tmpfname, "wb");
	char buf[256];
	struct diskArecord rec;
	long int oldpos = ftell(fp);
	fseek(fp, 0L, SEEK_SET);
	while (fread(&rec, sizeof(struct diskArecord), 1, fp))
	{
		fread(buf, rec.hostname, 1, fp);
		buf[rec.hostname] = 0; //null terminate it
		if (strcmp(buf, hostname))
		{
			fwrite(&rec, sizeof(struct diskArecord), 1, tmpf);
			fwrite(buf, rec.hostname, 1, tmpf);
		}
	}
	fflush(tmpf);
	freopen(NULL, "rb", tmpf);
	freopen(NULL, "wb", fp);
	while (fread(buf, 1, 1, tmpf)) fwrite(buf, 1, 1, fp);
	fflush(fp);
	fclose(tmpf);
	unlink(tmpfname);
	freopen(NULL, "rb", fp);
	fseek(fp, oldpos, SEEK_SET);
}
Example #19
0
int GzFlushDisplay2File(FILE* outfile, GzDisplay *display)
{

	/* write pixels to ppm file based on display class -- "P6 %d %d 255\r" */

	if( !outfile || ! display )
		return GZ_FAILURE;

	char buffer[1024];

	// create and write out header
	sprintf_s( buffer, 1024, "P6 %d %d 255\r", display->xres, display->yres );
	fwrite( buffer, sizeof( char ), strlen( buffer ), outfile );

	for( int row = 0; row < display->yres; row++ )
	{
		for( int col = 0; col < display->xres; col++ )
		{
			// clear the buffer just in case
			memset( buffer, 0, sizeof( 1024 ) );

			int idx = ARRAY( col, row );

			// we want binary representation in the file, so shift 4 bits over and write RGB chars to file
			sprintf_s( buffer, 1024, "%c%c%c", 
				display->fbuf[idx].red >> 4, 
				display->fbuf[idx].green >> 4, 
				display->fbuf[idx].blue >> 4 );
			fwrite( buffer, sizeof( char ), strlen( buffer ), outfile );
		}
	}

	return GZ_SUCCESS;
}
Example #20
0
// capture a single frame of video (and corresponding audio length)
// and send it to pipes
void I_CaptureFrame (void)
{
  unsigned char *snd;
  unsigned char *vid;
  static int partsof35 = 0; // correct for sync when samplerate % 35 != 0
  int nsampreq;

  if (!capturing_video)
    return;

  nsampreq = snd_samplerate / cap_fps;
  partsof35 += snd_samplerate % cap_fps;
  if (partsof35 >= cap_fps)
  {
    partsof35 -= cap_fps;
    nsampreq++;
  }

  snd = I_GrabSound (nsampreq);
  if (snd)
  {
    if (fwrite (snd, nsampreq * 4, 1, soundpipe.f_stdin) != 1)
      lprintf(LO_WARN, "I_CaptureFrame: error writing soundpipe.\n");
    //free (snd); // static buffer
  }
  vid = I_GrabScreen ();
  if (vid)
  {
    if (fwrite (vid, REAL_SCREENWIDTH * REAL_SCREENHEIGHT * 3, 1, videopipe.f_stdin) != 1)
      lprintf(LO_WARN, "I_CaptureFrame: error writing videopipe.\n");
    //free (vid); // static buffer
  }

}
Example #21
0
int main(void)
{
    FILE* file = fopen("./card.raw", "r");
    FILE* temp;
    
    if (file == NULL)
    {
        printf("Could not open card.raw\n");
        return 1;
    }
    
    BYTE* buffer = malloc(BLOCKSIZE);
    
    if (buffer == NULL)
    {
        printf("Error allocating memory\n");
        return 2;
    }
    
    char* filename = malloc(sizeof(char) * 8);
    int counter = 0;
    
    bool fileOpened = false;
    
    while(fread(buffer, sizeof(buffer), 1, file) == 1)
    {   
        if(isJPEG(buffer))
        {
            sprintf(filename, "%03d.jpg", counter);
            counter++;
            
            if(fileOpened)
            {
                fclose(temp);
                temp = fopen(filename, "w");
                fwrite(buffer, sizeof(buffer), 1, temp);
            }
            else
            {
                temp = fopen(filename, "w");
                fwrite(buffer, sizeof(buffer), 1, temp);
                fileOpened = true;
            }             
        }     
        else if (fileOpened)
        {
            fwrite(buffer, sizeof(buffer), 1, temp);
        }
    }
    
    if(temp)
    {
        fclose(temp);
    }
    fclose(file);
    free(filename);
    free(buffer);
    
    return 0;
}
Example #22
0
static void redirect_output(int fd, FILE * out)
{
    fd_set read_set;
    ssize_t size;
    char buff[1024];

    for (;;)
    {
        FD_ZERO(&read_set);
        FD_SET(fd, &read_set);
        if (select(fd+1, &read_set, NULL, NULL, NULL) < 0) continue;
        if (FD_ISSET(fd, &read_set))
        {
            size = read(fd, buff, sizeof(buff));
            if (size <= 0) break;
            if (buff[size-1] == '\0')
            {
                fwrite(buff, 1, strlen(buff), out);
                break;
            }
            else
            {
                fwrite(buff, 1, size, out);
            }
        }
    }
    //joel add for bcm platform.the web server will lost some data without flush.
    fflush(out);
}
Example #23
0
int
bits_fput (FILE *file,
    const BITS *bits)
{
    int
        block_nbr;                      /*  Bitstring block number           */
    word
        comp_size;                      /*  Size of compressed block         */
    BITBLOCK
        *block_ptr;                     /*  Points to bitstring block        */

    ASSERT (bits);
    ASSERT (file);

    /*  Write bitstring header to file                                       */
    fwrite (&bits-> block_count, sizeof (bits-> block_count), 1, file);
    fwrite (&bits-> free_list,   sizeof (bits-> free_list),   1, file);

    /*  Write bitstring blocks to file                                       */
    for (block_nbr = 0; block_nbr < bits-> block_count; block_nbr++)
      {
        block_ptr = bits-> block [block_nbr];
        comp_size = compress_block ((byte *) block_ptr,
                                    compressed, (word) block_ptr-> size);

        fwrite (&comp_size, sizeof (comp_size), 1, file);
        fwrite (compressed, comp_size,          1, file);
      }
    return 0;
}
Example #24
0
File: IPS.c Project: Archenoth/AIPS
/**
 * Creates a patch file with the passed in pStruct
 *
 * This function creates an IPS patch file
 */
int IPSCreatePatch(struct pStruct *params) {
    rewind(params->patchFile);
    fwrite("PATCH", 1, sizeof("PATCH"), params->patchFile);

    fwrite("EOF", 1, sizeof("EOF"), params->patchFile);
    return 0;
}
Example #25
0
void zipmapRepr(unsigned char *p) {
    unsigned int l;

    printf("{status %u}",*p++);
    while(1) {
        if (p[0] == ZIPMAP_END) {
            printf("{end}");
            break;
        } else {
            unsigned char e;

            l = zipmapDecodeLength(p);
            printf("{key %u}",l);
            p += zipmapEncodeLength(NULL,l);
            if (l != 0 && fwrite(p,l,1,stdout) == 0) perror("fwrite");
            p += l;

            l = zipmapDecodeLength(p);
            printf("{value %u}",l);
            p += zipmapEncodeLength(NULL,l);
            e = *p++;
            if (l != 0 && fwrite(p,l,1,stdout) == 0) perror("fwrite");
            p += l+e;
            if (e) {
                printf("[");
                while(e--) printf(".");
                printf("]");
            }
        }
    }
    printf("\n");
}
Example #26
0
File: IPS.c Project: Archenoth/AIPS
int IPSWriteRLE(struct patchData *patch, FILE *filePointer) {
    ASSERT(&patch->offset == 0, "RLE writing occurring without offset of 0.");
    fwrite(&patch->offset, 2, 1, filePointer); /* Offset should be 0 */
    fwrite(&patch->size, 2, 1, filePointer);
    fwrite(&patch->data, 1, 1, filePointer);
    return 0;
}
Example #27
0
void OutputCompTxt(DICT *dict, FILE *output)
{
  uint i;
  fwrite(&(dict->code_len),     sizeof(uint), 1, output);
  fwrite(&(dict->txt_len),      sizeof(uint), 1, output);
  fwrite(&(dict->char_size),    sizeof(uint), 1, output);
  fwrite(&(dict->mchar_size),   sizeof(uint), 1, output);
  fwrite(&(dict->cont_len),     sizeof(uint), 1, output);
  fwrite(&(dict->num_contexts), sizeof(uint), 1, output);
  fwrite(&(dict->seq_len),      sizeof(uint), 1, output);
  fwrite(dict->echar_table,     sizeof(uchar), dict->char_size, output);
  fwrite(dict->mchar_table,     sizeof(uchar), dict->char_size, output);

  for (i = 0; i < dict->num_contexts; i++) {
    fwrite(&(dict->rule[i]->num_rules), sizeof(uint), 1, output);
  }

  switch (dict->code_len) {
  case 8:
    outputCompTxt8(dict, output); 
    break;
  case 16:
    outputCompTxt16(dict, output);
    break;
  default:
    outputCompTxtVar(dict, output);
    break;
  }
}
Example #28
0
const bool EvaCachedFile::saveFragment(const unsigned int offset, 
					const unsigned int len, 
					unsigned char *buf)
{
	if(m_IsLoading) return false;
	if( ! isNewFragment(offset, len)){
		util_log(0,"EvaCachedFile::saveFragment -- already got this fragment!\n");
		return true; // if we got it already, always return true
	}

	string fullpath = m_DirPath + "\\" + m_CachedFileName;
	FILE* fp;
	if(!(fp=fopen(fullpath.c_str(),"ab"))){
		util_log(0,"EvaCachedFile::saveFragment -- cannot open \"%s\"!\n", fullpath.c_str());
		return false;
	}
	char strHeader[8];
	memcpy(strHeader, &offset, 4);
	memcpy(strHeader+4, &len, 4);
	fwrite(strHeader,8,1,fp);
	fwrite((char*)buf,len,1,fp);
	fclose(fp);

	if( ! updateInfoFile(offset, len)) return false;

	// let user control this
// 	if( isFinished() )
// 		return generateDestFile();

	return true;
}
Example #29
0
/** Record new compass data for use when inv_execute_on_data() is called
* @param[in] compass Compass data, if it was calibrated outside MPL, the units are uT scaled by 2^16.
*            Length 3.
* @param[in] status Lower 2 bits are the accuracy, with 0 being inaccurate, and 3 being most accurate.
*            The upper bit INV_CALIBRATED, is set if the data was calibrated outside MPL and it is
*            not set if the data being passed is raw. Raw data should be in device units, typically
*            in a 16-bit range.
* @param[in] timestamp Monotonic time stamp, for Android it's in nanoseconds.
* @return Returns INV_SUCCESS if successful or an error code if not.
*/
inv_error_t inv_build_compass(const long *compass, int status,
                              inv_time_t timestamp)
{
#ifdef INV_PLAYBACK_DBG
    if (inv_data_builder.debug_mode == RD_RECORD) {
        int type = PLAYBACK_DBG_TYPE_COMPASS;
        fwrite(&type, sizeof(type), 1, inv_data_builder.file);
        fwrite(compass, sizeof(compass[0]), 3, inv_data_builder.file);
        fwrite(&timestamp, sizeof(timestamp), 1, inv_data_builder.file);
    }
#endif

    if ((status & INV_CALIBRATED) == 0) {
        sensors.compass.raw[0] = (short)compass[0];
        sensors.compass.raw[1] = (short)compass[1];
        sensors.compass.raw[2] = (short)compass[2];
        inv_apply_calibration(&sensors.compass, inv_data_builder.save.compass_bias);
        sensors.compass.status |= INV_RAW_DATA;
    } else {
        sensors.compass.calibrated[0] = compass[0];
        sensors.compass.calibrated[1] = compass[1];
        sensors.compass.calibrated[2] = compass[2];
        sensors.compass.status |= INV_CALIBRATED;
        sensors.compass.accuracy = status & 3;
        inv_data_builder.save.compass_accuracy = status & 3;
    }
    sensors.compass.timestamp_prev = sensors.compass.timestamp;
    sensors.compass.timestamp = timestamp;
    sensors.compass.status |= INV_NEW_DATA | INV_SENSOR_ON;

    return INV_SUCCESS;
}
Example #30
0
/* this one saves the paremeters from builder window into a file */
int save_packet(GtkButton *button, gpointer user_data, FILE *file_p) {

    if (make_packet(button, user_data) == -1) {
        return -1;
    }

    struct pcap_hdr fh;
    fh.magic = PCAP_MAGIC;
    fh.version_major = 2;
    fh.version_minor = 4;
    fh.thiszone = 0;
    fh.sigfigs = 0;
    fh.snaplen = 102400;
    fh.network = pcap_link_type;
    fwrite(&fh, sizeof(fh), 1, file_p);

    struct pcaprec_hdr ph;
    ph.ts_sec = 0;
    ph.ts_usec = 0;
    ph.incl_len = number;
    ph.orig_len = number;
    fwrite(&ph, sizeof(ph), 1, file_p);

    fwrite(packet, number, 1, file_p);

    return 1;
}