Exemple #1
0
/*****************************************************************************
                    snap by mode 2
 how to snap:
 1)create snap group for each vichn,and bind them (not unbind until program end),
   that is muti snap group exit, instead of only one
 2)create one snap channel for each snap group
 3)register snap chn to its corresponding group, snapping, and then unregister
 4)repeat 3) to snap muti pictures of the channel

 features:
 1)need more memory than mode 1, because muti snap group and snap channel exit
 2)higher efficiency, because all snap chn run simultaneity.
*****************************************************************************/
HI_VOID* thread_StartSnapByMode2(HI_VOID *p)
{
    HI_S32 s32Ret;
    VENC_GRP VeGroup;
    VENC_CHN SnapChn;
    VI_DEV ViDev;
    VI_CHN ViChn;
    FILE *pFile = NULL;
    HI_S32 s32SnapCnt;
    HI_S32 s32SnapTotal;
    SNAP_SINGLE_CHN_S *pstSnapSingleChn = NULL;

    pstSnapSingleChn = (SNAP_SINGLE_CHN_S*)p;
    VeGroup = pstSnapSingleChn->VeGroup;
    SnapChn = pstSnapSingleChn->SnapChn;
    ViDev = pstSnapSingleChn->ViDev;
    ViChn = pstSnapSingleChn->ViChn;
    s32SnapTotal = pstSnapSingleChn->s32SnapTotal;

    /*note: bind snap group to vichn, not unbind while snapping*/
    s32Ret = HI_MPI_VENC_BindInput(VeGroup, ViDev, ViChn);
    if (s32Ret != HI_SUCCESS)
    {
        printf("HI_MPI_VENC_BindInput err 0x%x\n", s32Ret);
        return NULL;
    }

    s32SnapCnt = 0;
    while (HI_TRUE == pstSnapSingleChn->bThreadStart)
    {
        s32Ret = HI_MPI_VENC_RegisterChn(VeGroup, SnapChn);
        if (s32Ret != HI_SUCCESS)
        {
            printf("HI_MPI_VENC_RegisterChn err 0x%x\n", s32Ret);
            return NULL;
        }

        s32Ret = HI_MPI_VENC_StartRecvPic(SnapChn);
        if (s32Ret != HI_SUCCESS)
        {
            printf("HI_MPI_VENC_StartRecvPic err 0x%x\n", s32Ret);
            return NULL;
        }

        {
            /*save jpeg picture*/
            char acFile[128]  = {0};
            //struct timeval timenow;
            sprintf(acFile, "Vichn%d_num%d.jpg", ViChn, s32SnapCnt);
            pFile = fopen(acFile, "wb");
            if (pFile == NULL)
            {
                printf("open file err\n");
                return NULL;
            }

            s32Ret = SAMPLE_GetSnapPic(SnapChn, pFile);
            if (s32Ret != HI_SUCCESS)
            {
                printf("SAMPLE_GetSnapPic err 0x%x\n", s32Ret);
                fclose(pFile);
                return NULL;
            }
            fclose(pFile);
        }

        s32Ret = HI_MPI_VENC_StopRecvPic(SnapChn);
        if (s32Ret != HI_SUCCESS)
        {
            printf("HI_MPI_VENC_StopRecvPic err 0x%x\n", s32Ret);
            return NULL;
        }

        s32Ret = HI_MPI_VENC_UnRegisterChn(SnapChn);
        if (s32Ret != HI_SUCCESS)
        {
            printf("HI_MPI_VENC_UnRegisterChn err 0x%x\n", s32Ret);
            return NULL;
        }

        s32SnapCnt++;
    }

    s32Ret = HI_MPI_VENC_UnbindInput(VeGroup);
    if (s32Ret != HI_SUCCESS)
    {
        printf("HI_MPI_VENC_UnbindInput err 0x%x\n", s32Ret);
        return NULL;
    }

    return NULL;
}
Exemple #2
0
VOID UpdateFilebase (USHORT KeepDate)
{
   FILE *fp;
   DIR *dir;
   ULONG Total, Added;
   CHAR *p, Path[128], Temp[128];
   time_t today;
   struct stat statbuf;
   struct tm *ltm;
   struct dirent *ent;
   class TFileData *Data;
   class TFileBase *File;
   class TPacker *Packer;

   printf (" * Updating filebase\r\n");

   unlink ("file_id.diz");
   Packer = new TPacker (Cfg->SystemPath);

   if ((Data = new TFileData (Cfg->SystemPath)) != NULL) {
      if (Data->First () == TRUE)
         do {
            Total = 0L;
            Added = 0L;
            cprintf (" +-- %-15.15s %-32.32s ", Data->Key, Data->Display);
            if ((File = new TFileBase (Cfg->SystemPath, Data->Key)) != NULL) {
               strcpy (Temp, Data->Download);
               if (Temp[strlen (Temp) - 1] == '\\' || Temp[strlen (Temp) - 1] == '/')
                  Temp[strlen (Temp) - 1] = '\0';

               if (File->First () == TRUE)
                  do {
                     sprintf (Path, "%s%s", Data->Download, File->Name);
                     if (stat (AdjustPath (Path), &statbuf))
                        File->Delete ();
                  } while (File->Next () == TRUE);

               File->SortByName ();
               if ((dir = opendir (AdjustPath (Temp))) != NULL) {
                  while ((ent = readdir (dir)) != NULL) {
                     if (!strcmp (ent->d_name, ".") || !strcmp (ent->d_name, ".."))
                        continue;
                     if (!stricmp (ent->d_name, "files.bbs") || !stricmp (ent->d_name, "descript.ion"))
                        continue;
                     if (File->Read (ent->d_name) == FALSE) {
                        sprintf (Path, "%s%s", Data->Download, ent->d_name);
                        if (!stat (AdjustPath (Path), &statbuf)) {
                           File->Clear ();
                           strcpy (File->Area, Data->Key);
                           strcpy (File->Name, ent->d_name);
                           strcpy (File->Complete, Path);
                           File->Size = statbuf.st_size;
                           ltm = localtime ((time_t *)&statbuf.st_mtime);
                           File->Date.Day = (UCHAR)ltm->tm_mday;
                           File->Date.Month = (UCHAR)(ltm->tm_mon + 1);
                           File->Date.Year = (USHORT)(ltm->tm_year + 1900);
                           File->Date.Hour = (UCHAR)ltm->tm_hour;
                           File->Date.Minute = (UCHAR)ltm->tm_min;
                           if (KeepDate == FALSE) {
                              today = time (NULL);
                              ltm = localtime (&today);
                              File->UplDate.Day = (UCHAR)ltm->tm_mday;
                              File->UplDate.Month = (UCHAR)(ltm->tm_mon + 1);
                              File->UplDate.Year = (USHORT)(ltm->tm_year + 1900);
                              File->UplDate.Hour = (UCHAR)ltm->tm_hour;
                              File->UplDate.Minute = (UCHAR)ltm->tm_min;
                           }
                           else {
                              File->UplDate.Day = File->Date.Day;
                              File->UplDate.Month = File->Date.Month;
                              File->UplDate.Year = File->Date.Year;
                              File->UplDate.Hour = File->Date.Hour;
                              File->UplDate.Minute = File->Date.Minute;
                           }
                           File->Uploader = "Sysop";
                           File->CdRom = Data->CdRom;
                           File->Description->Add ("Description missing");
                           if (Packer != NULL) {
                              if (Packer->CheckArc (Path) == TRUE) {
#if defined(__LINUX__)
                                 mkdir ("lfiletmp", 0666);
#else
                                 mkdir ("lfiletmp");
#endif
                                 if (strstr (Packer->UnpackCmd, "%3") == NULL && strstr (Packer->UnpackCmd, "%f") == NULL)
                                    strcat (Packer->UnpackCmd, " %3");
                                 Packer->DoUnpack (Path, "lfiletmp", "file_id.diz");
                                 strcpy (Temp, "lfiletmp\\file_id.diz");
                                 if (!stat (AdjustPath (Temp), &statbuf)) {
                                    if ((fp = fopen (Temp, "rt")) != NULL) {
                                       File->Description->Clear ();
                                       while (fgets (Temp, sizeof (Temp) - 1, fp) != NULL) {
                                          if ((p = strchr (Temp, '\n')) != NULL)
                                             *p = '\0';
                                          if ((p = strchr (Temp, '\r')) != NULL)
                                             *p = '\0';
                                          File->Description->Add (Temp);
                                       }
                                       fclose (fp);
                                    }
                                    strcpy (Temp, "lfiletmp\\file_id.diz");
                                    unlink (AdjustPath (Temp));
                                 }
                                 rmdir ("lfiletmp");
                              }
                           }
                           File->Add ();
                           Added++;
                        }
                     }
                     Total++;
                  }
                  closedir (dir);
               }
               delete File;
            }
            cprintf ("Total: %5lu Added: %5lu\r\n", Total, Added);
         } while (Data->Next () == TRUE);
      delete Data;
   }

   if (Packer != NULL)
      delete Packer;
}
Exemple #3
0
 ~File() {
     if (f != nullptr)
         fclose(f);
 }
int main(int argc, char** argv) {
	int i = 0, j = 0;
	ull gen_size = 0, code_size = 0, data_size = 0;
	ull blocks = 0, wordsize = 0, dim = 0;
	unsigned char *G = NULL, *D = NULL, *DD = NULL, *C = NULL, *NC = NULL;
	unsigned short *masks = NULL;
	unsigned char *code_tmp = NULL, *data_block_tmp = NULL;
	double accumulator = 0;
	char buffer[100];

	FILE *fout = NULL;
	
	srand (time(NULL));

	ull r = 0, m = 16, k = 50, max_iter = 700;
	data_size = 4096;

	char **ptr = NULL;
	
	if (argc == 3) {
		r = strtol(argv[1], ptr, 10);
		m = strtol(argv[2], ptr, 10);
	}

	//rm_test_0(r, m, k, max_iter, stdout);

	for (i = r; i < m; ++i) {
		sprintf(buffer, "output_%2d", i);
		fout = fopen(buffer, "w");
		fprintf(fout, "%d\n", i);
		for (j = 0; j <= i; ++j) {
			printf("%d %d\n", i, j);
			fprintf(fout, "%d %d\n", i, j);
			rm_test_0(j, i, k, max_iter, fout);
			fprintf(fout, "\n");
		}
		fclose(fout);
	}

	//rm_test_0(r, m, k, max_iter);
	// //for (m = 12; m < 16; ++m) 
	// {
	// 	gen_size = generation_mem_size(m, m);
	// 	G = (unsigned char *) malloc(gen_size);
	// 	generate_matrix(m, m, G);

	// 	masks = (unsigned short *) malloc((1 << m) * sizeof(unsigned short));
	// 	generate_masks(m, masks);

	// 	// for (r = 0; r <= m; ++r) 
	// 	{
				
	// 		D =	(unsigned char *) malloc(data_size);
	// 		DD = (unsigned char *) malloc(data_size);

	// 		for (int i = 0; i < data_size; ++i)
	// 			D[i] = (unsigned char) rand();
		     			

	// 		code_size = encode_mem_size(data_size, r, m);
	// 		C = (unsigned char *) malloc(code_size);
	// 		NC = (unsigned char *) malloc(code_size);


	// 		encode(r, m, G, data_size, D, C, masks);
			
	// 		blocks = rm_blocks(data_size, r, m);
	// 		wordsize = rm_wordsize(r, m);
	// 		dim = rm_dim(r, m);


	// 		code_tmp = (unsigned char *) malloc(wordsize / 8 + (wordsize % 8 == 0 ? 0 : 1));
	// 		data_block_tmp = (unsigned char *) malloc(dim / 8 + (dim % 8 == 0 ? 0 : 1));

	// 		decode(r, m, G, data_size, DD, C, masks, code_tmp, data_block_tmp);

	// 		// print(1, 8 * data_size, D);//printf("\n");
	// 		// print(1, 8 * data_size, DD);printf("\n\n");


	// 		//printf("r = %d, m = %d\n", r, m);
	// 		//printf("\nAccuracy %1.9lf:\n\n", accuracy(data_size, D, DD));


	// 		for (ull i = 0; i <= k; i++) {
	// 			accumulator = 0;
	// 			printf("%1.9lf ", (double) i / (double) k);

	// 			for (ull j = 0; j < max_iter; ++j) {
	// 				memcpy(NC, C, code_size);
	// 				add_noise(NC, code_size, (double) i / (double) k);	
	// 				decode(r, m, G, data_size, DD, NC, masks, code_tmp, data_block_tmp);
	// 				accumulator += accuracy(data_size, dim, D, DD);
	// 			}

	// 			printf("%1.9lf \n", accumulator / max_iter);
	// 		}

	// 		FREE_IF_ALLOCATED(C);
	// 		FREE_IF_ALLOCATED(D);
	// 		FREE_IF_ALLOCATED(DD);
			
	// 		FREE_IF_ALLOCATED(NC);

	// 		FREE_IF_ALLOCATED(code_tmp);
	// 		FREE_IF_ALLOCATED(data_block_tmp);
	// 	}

	// 	FREE_IF_ALLOCATED(masks);
	// 	FREE_IF_ALLOCATED(G);
	// }
	return 0;
}
Exemple #5
0
/*
 * Function    : libaroma_stream_file
 * Return Value: LIBAROMA_STREAMP
 * Descriptions: new stream from file
 */
LIBAROMA_STREAMP libaroma_stream_file(
    char * path) {
#ifdef LIBAROMA_SYSCAL_HAVE_MMAP
  if (!path) {
    ALOGW("libaroma_stream_file path is invalid");
    return NULL;
  }
  LIBAROMA_STREAMP ret;
  /* Read File Stat */
  int filesize=libaroma_filesize(path);
  if (filesize < 0) {
    ALOGI("libaroma_stream_file (%s) not found", path);
    return NULL;
  }
  /* Open File */
  int fd = open(path, O_RDONLY, 0);
  if (fd < 0) {
    ALOGW("libaroma_stream_file unable to open (%s)", path);
    return NULL;
  }
  /* MAP */
  bytep mem = (bytep) mmap(NULL, filesize,
                           PROT_READ, MAP_FILE | MAP_SHARED, fd, 0);
  /* Close FD */
  close(fd);
  if (mem == MAP_FAILED) {
    ALOGW("libaroma_stream_file unable to mmap (%s)", path);
    return NULL;
  }
  /* Return */
  ret           = (LIBAROMA_STREAMP) malloc(sizeof(LIBAROMA_STREAM));
  ret->data     = mem;
  ret->size     = filesize;
  ret->ismmap   = 1;
  snprintf(ret->uri,
      LIBAROMA_STREAM_URI_LENGTH, "file://%s", path);
  return ret;
#else
  if (!path) {
    ALOGW("libaroma_stream_file path is invalid");
    return 0;
  }
  LIBAROMA_STREAMP ret;
  /* Read File Stat */
  int filesize=libaroma_filesize(path);
  if (filesize < 0) {
    ALOGI("libaroma_stream_file (%s) not found", path);
    return NULL;
  }
  
  /* Allocating Memory */
  bytep mem = malloc(filesize);
  FILE * f = fopen(path, "rb");
  if (f == NULL) {
    ALOGW("libaroma_stream_file fopen error (%s)", path);
    goto error;
  }
  
  if (((int) fread(mem, 1, filesize, f)) != filesize) {
    ALOGW("libaroma_stream_file fread error (%s)", path);
    fclose(f);
    goto error;
  }
  fclose(f);
  goto done;
error:
  free(mem);
  return NULL;
done:
  ret           = (LIBAROMA_STREAMP) malloc(sizeof(LIBAROMA_STREAM));
  ret->data     = mem;
  ret->size     = filesize;
  ret->ismmap   = 0;
  snprintf(ret->uri,
      LIBAROMA_STREAM_URI_LENGTH, "file://%s", path);
  return ret;
#endif
} /* End of libaroma_stream_file */
bool CToolSetTileBlock::ReSizeSave( const string& path, int nWidth, int nDepth )
{
	COperator *pOperator   = CMapEditApp::GetInst()->GetOperator();
	CTerrainMesh* pTerrain = CMapEditApp::GetInst()->GetEditingMesh();
	if( pTerrain->IsWater() )
	{
		MessageBox(NULL,"将当前状态改成地形状态,而非水面层状态,否则不能保存地图阻挡信息","提示",MB_OK);
		return false;
	}

	//////////////////////////////////////////////////////////////////////////
	//保存扩展备份文件
	string strFileName = path;
	locale loc;
	use_facet<ctype<TCHAR> >( loc ).tolower
		( &strFileName[0], &strFileName[strFileName.length()] );

	size_t npos = strFileName.rfind(".");
	if( npos != -1 )
		strFileName = strFileName.substr(0, npos);

	string strBackUpName = strFileName + "_扩展备份.block";
	this->Save(strBackUpName);
	//////////////////////////////////////////////////////////////////////////

	
	strFileName += ".block";
	FILE * fp = NULL;
	fp = fopen(strFileName.c_str(),"wb");

	if (!fp)
	{
		string log = strFileName + "无法保存";
		MessageBox(NULL,log.c_str(),"提示",MB_OK);
		return false;
	}

	DWORD dwMapWidth = nWidth * REGION_SPACE;
	DWORD dwMapDepth = nDepth * REGION_SPACE;
	DWORD newGridCnt = dwMapWidth * dwMapDepth;

	///扩展后旧地图格子索引在新地图中的新索引映射 first new grid   index second old grid index
	map<int, int> m_NewMapGridIndexMap;
	map<int, int>::iterator beg, end = pOperator->m_OldMapGridIndexMap.end();
	for( beg = pOperator->m_OldMapGridIndexMap.begin(); beg != end; ++beg )
		m_NewMapGridIndexMap[beg->second] = beg->first;

	//////////////////////////////////////////////////////////////////////////
	///version
	int   nNoBlock  = 0;
	DWORD dwVersion = BLOCK_VERSION;

	fwrite(&dwVersion, sizeof(dwVersion), 1, fp);
	int nGridIndex = 0;
	for ( DWORD i  = 0; i < newGridCnt; ++i )
	{
		beg = m_NewMapGridIndexMap.find(i);
		if( beg != m_NewMapGridIndexMap.end() )
		{
			nGridIndex = beg->second;
			SGrid &grid = pTerrain->GetGrid(nGridIndex);

			fwrite(&grid.nBlockType, sizeof(int), 1, fp);
		}
		else
			fwrite(&nNoBlock, sizeof(int), 1, fp);
	}
	//////////////////////////////////////////////////////////////////////////
	fclose(fp);

	return true;
}
Exemple #7
0
void M_LoadDefaults (void)
{
  int   i;
  int   len;
  FILE* f;
  char  def[80];
  char  strparm[100];
  char* newstring = NULL;   // killough
  int   parm;
  boolean isstring;

  // set everything to base values

  numdefaults = sizeof(defaults) / sizeof(defaults[0]);
  for (i = 0 ; i < numdefaults ; i++) {
    if (defaults[i].location.ppsz)
      *defaults[i].location.ppsz = strdup(defaults[i].defaultvalue.psz);
    if (defaults[i].location.pi)
      *defaults[i].location.pi = defaults[i].defaultvalue.i;
  }

  // check for a custom default file

#if ((defined GL_DOOM) && (defined _MSC_VER))
#define BOOM_CFG "glboom.cfg"
#else
#define BOOM_CFG "prboom.cfg"
#endif

  i = M_CheckParm ("-config");
  if (i && i < myargc-1)
    defaultfile = strdup(myargv[i+1]);
  else {
    const char* exedir = I_DoomExeDir();
    /* get config file from same directory as executable */
#if 1
	int len = doom_snprintf(NULL, 0, BOOM_CFG);
	defaultfile = malloc(len+1);
	doom_snprintf(defaultfile, len+1, BOOM_CFG);
#else
    int len = doom_snprintf(NULL, 0, "%s/" BOOM_CFG, exedir);
    defaultfile = malloc(len+1);
    doom_snprintf(defaultfile, len+1, "%s/" BOOM_CFG, exedir);
#endif
  }

  lprintf (LO_CONFIRM, " default file: %s\n",defaultfile);

  // read the file in, overriding any set defaults

  f = fopen (defaultfile, "r");
  if (f)
    {
    while (!feof(f))
      {
      isstring = false;
      if (fscanf (f, "%79s %[^\n]\n", def, strparm) == 2)
        {

        //jff 3/3/98 skip lines not starting with an alphanum

        if (!isalnum(def[0]))
          continue;

        if (strparm[0] == '"') {
          // get a string default

          isstring = true;
          len = strlen(strparm);
          newstring = (char *) malloc(len);
          strparm[len-1] = 0; // clears trailing double-quote mark
          strcpy(newstring, strparm+1); // clears leading double-quote mark
  } else if ((strparm[0] == '0') && (strparm[1] == 'x')) {
    // CPhipps - allow ints to be specified in hex
    sscanf(strparm+2, "%x", &parm);
  } else {
          sscanf(strparm, "%i", &parm);
    // Keycode hack removed
  }

        for (i = 0 ; i < numdefaults ; i++)
          if ((defaults[i].type != def_none) && !strcmp(def, defaults[i].name))
            {
      // CPhipps - safety check
            if (isstring != IS_STRING(defaults[i])) {
        lprintf(LO_WARN, "M_LoadDefaults: Type mismatch reading %s\n", defaults[i].name);
        continue;
      }
            if (!isstring)
              {

              //jff 3/4/98 range check numeric parameters

              if ((defaults[i].minvalue==UL || defaults[i].minvalue<=parm) &&
                  (defaults[i].maxvalue==UL || defaults[i].maxvalue>=parm))
                *(defaults[i].location.pi) = parm;
              }
            else
              {
                union { const char **c; char **s; } u; // type punning via unions

                u.c = defaults[i].location.ppsz;
                free(*(u.s));
                *(u.s) = newstring;
              }
            break;
            }
        }
      }

    fclose (f);
    }
  //jff 3/4/98 redundant range checks for hud deleted here
}
Exemple #8
0
/* Write a sequence of commands able to fully rebuild the dataset into
 * "filename". Used both by REWRITEAOF and BGREWRITEAOF. */
static int rewriteAppendOnlyFile(char *filename) {
    dictIterator *di = NULL;
    dictEntry *de;
    FILE *fp;
    char tmpfile[256];
    int j;
    time_t now = time(NULL);

    /* Note that we have to use a different temp name here compared to the
     * one used by rewriteAppendOnlyFileBackground() function. */
    snprintf(tmpfile,256,"temp-rewriteaof-%d.aof", (int) getpid());
    fp = fopen(tmpfile,"w");

    for (j = 0; j < server.dbnum; j++) {
        char selectcmd[] = "*2\r\n$6\r\nSELECT\r\n";
        redisDb *db = server.db+j;
        dict *d = db->dict;

        if (dictSize(d) == 0) continue;
        di = dictGetIterator(d);


        /* SELECT the new DB */
        fwrite(selectcmd,sizeof(selectcmd)-1,1,fp);
        fwriteBulkLong(fp,j);

        /* Iterate this DB writing every entry */
        while((de = dictNext(di)) != NULL) {
            robj *key, *o;
            time_t expiretime;
            int swapped;

            key = dictGetEntryKey(de);
            /* If the value for this key is swapped, load a preview in memory.
             * We use a "swapped" flag to remember if we need to free the
             * value object instead to just increment the ref count anyway
             * in order to avoid copy-on-write of pages if we are forked() */
            if (!server.vm_enabled || key->storage == REDIS_VM_MEMORY ||
                key->storage == REDIS_VM_SWAPPING) {
                o = dictGetEntryVal(de);
                swapped = 0;
            } else {
                o = vmPreviewObject(key);
                swapped = 1;
            }
            expiretime = getExpire(db,key);

            /* Save the key and associated value */
            if (o->type == REDIS_STRING) {
                /* Emit a SET command */
                char cmd[]="*3\r\n$3\r\nSET\r\n";
                fwrite(cmd, sizeof(cmd)-1,1,fp);
                /* Key and value */
                fwriteBulkObject(fp,key);
                fwriteBulkObject(fp,o);
            } 
            else if (o->type == REDIS_LIST) {
                /* Emit the RPUSHes needed to rebuild the list */
                list *list = o->ptr;
                listNode *ln;
                listIter li;

                listRewind(list,&li);
                while((ln = listNext(&li))) {
                    char cmd[]="*3\r\n$5\r\nRPUSH\r\n";
                    robj *eleobj = listNodeValue(ln);

                    fwrite(cmd, sizeof(cmd)-1, 1, fp);
                    fwriteBulkObject(fp,key);
                    fwriteBulkObject(fp,eleobj);
                }
            } 
            else if (o->type == REDIS_SET) {
                /* Emit the SADDs needed to rebuild the set */
                dict *set = o->ptr;
                dictIterator *di = dictGetIterator(set);
                dictEntry *de;

                while((de = dictNext(di)) != NULL) {
                    char cmd[]="*3\r\n$4\r\nSADD\r\n";
                    robj *eleobj = dictGetEntryKey(de);

                    fwrite(cmd,sizeof(cmd)-1,1,fp) ;
                    fwriteBulkObject(fp,key) ;
                    fwriteBulkObject(fp,eleobj);
                }
                dictReleaseIterator(di);
            } 
            else if (o->type == REDIS_ZSET) {
                /* Emit the ZADDs needed to rebuild the sorted set */
                zset *zs = o->ptr;
                dictIterator *di = dictGetIterator(zs->dict);
                dictEntry *de;

                while((de = dictNext(di)) != NULL) {
                    char cmd[]="*4\r\n$4\r\nZADD\r\n";
                    robj *eleobj = dictGetEntryKey(de);
                    double *score = dictGetEntryVal(de);

                    if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
                    if (fwriteBulkObject(fp,key) == 0) goto werr;
                    if (fwriteBulkDouble(fp,*score) == 0) goto werr;
                    if (fwriteBulkObject(fp,eleobj) == 0) goto werr;
                }
                dictReleaseIterator(di);
            } else if (o->type == REDIS_HASH) {
                char cmd[]="*4\r\n$4\r\nHSET\r\n";

                /* Emit the HSETs needed to rebuild the hash */
                if (o->encoding == REDIS_ENCODING_ZIPMAP) {
                    unsigned char *p = zipmapRewind(o->ptr);
                    unsigned char *field, *val;
                    unsigned int flen, vlen;

                    while((p = zipmapNext(p,&field,&flen,&val,&vlen)) != NULL) {
                        if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
                        if (fwriteBulkObject(fp,key) == 0) goto werr;
                        if (fwriteBulkString(fp,(char*)field,flen) == -1)
                            return -1;
                        if (fwriteBulkString(fp,(char*)val,vlen) == -1)
                            return -1;
                    }
                } else {
                    dictIterator *di = dictGetIterator(o->ptr);
                    dictEntry *de;

                    while((de = dictNext(di)) != NULL) {
                        robj *field = dictGetEntryKey(de);
                        robj *val = dictGetEntryVal(de);

                        if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
                        if (fwriteBulkObject(fp,key) == 0) goto werr;
                        if (fwriteBulkObject(fp,field) == -1) return -1;
                        if (fwriteBulkObject(fp,val) == -1) return -1;
                    }
                    dictReleaseIterator(di);
                }
            } else {
                redisAssert(0);
            }
            /* Save the expire time */
            if (expiretime != -1) {
                char cmd[]="*3\r\n$8\r\nEXPIREAT\r\n";
                /* If this key is already expired skip it */
                if (expiretime < now) continue;
                fwrite(cmd,sizeof(cmd)-1,1,fp) ;
                fwriteBulkObject(fp,key) ;
                fwriteBulkLong(fp,expiretime) ;
            }
            if (swapped) decrRefCount(o);
        }
        dictReleaseIterator(di);
    }

    /* Make sure data will not remain on the OS's output buffers */
    fflush(fp);
    fsync(fileno(fp));
    fclose(fp);
    
    /* Use RENAME to make sure the DB file is changed atomically only
     * if the generate DB file is ok. */
    rename(tmpfile,filename) ;
    
    redisLog(REDIS_NOTICE,"SYNC append only file rewrite performed");
    return REDIS_OK;
}
Exemple #9
0
/*
 * readConfigFile(): read configuration from file, skipping auctions
 *
 * returns:
 *	0 file successfully read, even if no configuration options found
 *	1 file not found
 *	2 other error
 */
int
readConfigFile(const char *filename, optionTable_t *table)
{
	char *buf = NULL;
	size_t bufsize = 0, count = 0;
	int c, ret = 0;
	FILE *fp = fopen(filename, "r");

	if (fp == NULL) {
		/* file not found is OK */
		if (errno == ENOENT)
			return 1;
		printLog(stderr, "Cannot open %s: %s\n", filename,
			 strerror(errno));
		return 2;
	}

	while ((c = getc(fp)) != EOF) {
		if (isspace(c))
			continue;
		/* skip comments and anything starting with a number,
		 * assuming this is an auction entry */
		if ((c == '#') || isdigit(c))
			c = skipline(fp);
		else if (isalpha(c)) {
			char *name = NULL, *value = NULL;

			count = 0;
			do {
				addchar(buf, bufsize, count, (char)c);
				c = getc(fp);
			} while (c != EOF && !isspace(c) && c != '=');
			addchar(buf, bufsize, count, '\0');
			name = buf;

			if (c != EOF && c != '\n' && c != '\r') {
				do {
					c = getc(fp);
				} while (c == ' ' || c == '\t');
				if (c == '=') {
					do {
						c = getc(fp);
					} while (c == ' ' || c == '\t');
				}

				if (c != EOF && c != '\n' && c != '\r') {
					value = &buf[count];
					do {
						addchar(buf, bufsize, count, (char)c);
						c = getc(fp);
					} while (c != EOF && c != '\n' && c != '\r');
					/* strip trailing whitespace */
					while (isspace((int)(buf[count - 1])))
						--count;
					term(buf, bufsize, count);
				}
			}
			if (parseConfigValue(name, value, table, filename, buf))
				ret = 2;
		}

		/* don't read EOF twice! */
		if (c == EOF)
			break;
	}

	if (ferror(fp)) {
		printLog(stderr, "Cannot read %s: %s\n", filename,
			 strerror(errno));
		ret = 2;
	}
	fclose(fp);
	free(buf);
	return ret;
} /* readConfigFile() */
//-----------------------------------------------------------------------------
static void process_dir_watcher_results(
    watch_entry *watch_entry_p,
	DWORD           buffer_size){
//-----------------------------------------------------------------------------
    HANDLE hChangeLog;
    PFILE_NOTIFY_INFORMATION buffer_p;
    DWORD buffer_index;
    BOOL more;
    SSIZE_T path_len;
    int compare_result;
    BOOL exclude;
    struct exclude_entry * exclude_entry_p;
    DWORD error_code;
	errno_t copy_result;
	LPWSTR fmt, slash_pos;

	hChangeLog = INVALID_HANDLE_VALUE;
    more = TRUE;
    buffer_index = 0;

	// If buffer size is 0, indicates that too many changes occurred to fit in the buffer
	// Write out the top level dir to trigger the monitor to do a full pass of it
	if (buffer_size == 0){
		more = FALSE;
		copy_result = wcsncpy_s(full_file_name, ARRAYSIZE(full_file_name),
			watch_entry_p->dir_path, watch_entry_p->dir_path_len);
		if (copy_result != 0){
			report_error(L"wcsncpy_s failed", copy_result);
			ExitProcess(28);
			}
		write_path_to_temp_file(full_file_name, ARRAYSIZE(full_file_name), &hChangeLog);
	}

	while (more) {
		buffer_p = (PFILE_NOTIFY_INFORMATION) &watch_entry_p->changes_buffer[buffer_index];
		// Cannot use just sizeof(FILE_NOTIFY_INFORMATION) as it includes 2 bytes of struct padding,
		// causing this check to fail for single-character filenames
		size_t entry_size = offsetof(FILE_NOTIFY_INFORMATION, FileName) + buffer_p->FileNameLength;
        if ((buffer_index + entry_size) > buffer_size) {
            _wfopen_s(&error_file, error_path, L"w");
            fwprintf(
                error_file, 
                L"process_dir_watcher_results buffer overrun %d %d\n",  
                buffer_index,
                buffer_size
            );
            fclose(error_file);
            ExitProcess(18);
        }

        copy_result = wcsncpy_s(relative_file_name, ARRAYSIZE(relative_file_name),
			buffer_p->FileName, buffer_p->FileNameLength/sizeof(wchar_t));
		if (copy_result != 0){
			report_error(L"wcsncpy_s failed", copy_result);
			ExitProcess(25);
			}

        // 2010-09-05 dougfort -- if the dir_path ends in a slash 
        // (probably something like c:\) then we don't want to
        // interpolate another slash
		if (watch_entry_p->dir_path[watch_entry_p->dir_path_len-1] == L'\\')
			fmt = L"%s%s";
		else
			fmt = L"%s\\%s";
		path_len = _snwprintf_s(full_file_name, ARRAYSIZE(full_file_name), _TRUNCATE,
			fmt, watch_entry_p->dir_path, relative_file_name);
		if (path_len == -1){
			report_error(L"_snwprintf_s failed, path too long",
				(DWORD)(watch_entry_p->dir_path_len + wcslen(relative_file_name)));
			ExitProcess(26);
		}

		// We want the directory where the event took place, 
		// for consistency with OSX.
		// Needs to be done before calling GetLongPathName since in the case of
		// a rename or delete the actual file itself is already gone
		if (full_file_name[path_len-1] != L'\\') {
			slash_pos = wcsrchr(full_file_name, L'\\');
			if (slash_pos)
				*slash_pos = L'\0';
		}

		// Need to translate short names before checking excludes
		// According to MSDN docs, you can reuse the same buffer for output
		path_len = GetLongPathNameW(
			full_file_name,
			full_file_name,
			ARRAYSIZE(full_file_name)
		);
		// Note that most of errors that occurred here were due to a buffer overflow
		// which has since been fixed.  In case of error, pass orig filename unchanged and
		// let code that picks up output deal with removed folders, etc
		if (path_len == 0) {
			error_code = GetLastError();
			report_error(L"GetLongPathNameW", error_code);
			path_len=wcslen(full_file_name);
		}
		else if (path_len > ARRAYSIZE(full_file_name)){
			// Shouldn't happen since buffer is maximum possible path length
			report_error(L"GetLongPathNameW result would overflow buffer", (DWORD)path_len);
			ExitProcess(27);
		}

		// Can check for excludes last since we only ever exclude folders
        exclude = FALSE;
        for (
            exclude_entry_p=exclude_entry_list_p; 
            exclude_entry_p != NULL; 
            exclude_entry_p = exclude_entry_p->next_p
        ) {
            compare_result = _wcsnicmp(
                full_file_name,
                exclude_entry_p->dir_path,
                exclude_entry_p->dir_path_len
            );
            if (0 == compare_result) {
                exclude = TRUE;
                break;
            }
        }

        if (exclude) {
            if (0 == buffer_p->NextEntryOffset) {
                more = FALSE;
            } else {
                buffer_index += buffer_p->NextEntryOffset;
            }
            continue;
        }

		write_path_to_temp_file(full_file_name, ARRAYSIZE(full_file_name), &hChangeLog);

        if (0 == buffer_p->NextEntryOffset) {
            more = FALSE;
        } else {
            buffer_index += buffer_p->NextEntryOffset;
        }
    } // while (more)

    if (hChangeLog != INVALID_HANDLE_VALUE) {
        CloseHandle(hChangeLog);

        notification_sequence++;
        wsprintf(          
            notification_file_path,         // LPTSTR pszDest,
            L"%s\\%08d.txt",                // LPCTSTR pszFormat 
            notification_path,
            notification_sequence
        );
        if (_wrename(temp_file_path, notification_file_path) != 0) {
            _wfopen_s(&error_file, error_path, L"w");
            _wcserror_s(
               error_buffer, sizeof error_buffer/sizeof(wchar_t), errno
            ); 
            fwprintf(
                error_file, 
                L"_wrename(%s, %s) failed: (%d) %s\n",  
                temp_file_path,
                notification_file_path,
                errno,
                error_buffer 
            );
            fclose(error_file);
            ExitProcess(24);
        }
    }

} // static void process_dir_watcher_results(
Exemple #11
0
/* Replay the append log file. On error REDIS_OK is returned. On non fatal
 * error (the append only file is zero-length) REDIS_ERR is returned. On
 * fatal error an error message is logged and the program exists. */
int loadAppendOnlyFile(char *filename) {
    struct redisClient *fakeClient;
    FILE *fp = fopen(filename,"r");
    struct redis_stat sb;
    unsigned long long loadedkeys = 0;

    if (redis_fstat(fileno(fp),&sb) != -1 && sb.st_size == 0)
        return REDIS_ERR;

    fakeClient = createFakeClient();
    while(1) {
        int argc, j;
        unsigned long len;
        robj **argv;
        char buf[128];
        sds argsds;
        struct redisCommand *cmd;

        if (fgets(buf,sizeof(buf),fp) == NULL) {
            if (feof(fp))
                break;
            else
                goto readerr;
        }
        if (buf[0] != '*') goto fmterr;
        argc = atoi(buf+1);
        argv = zmalloc(sizeof(robj*)*argc);
        for (j = 0; j < argc; j++) {
            if (fgets(buf,sizeof(buf),fp) == NULL) goto readerr;
            if (buf[0] != '$') goto fmterr;
            len = strtol(buf+1,NULL,10);
            argsds = sdsnewlen(NULL,len);
            if (len && fread(argsds,len,1,fp) == 0) goto fmterr;
            argv[j] = createObject(REDIS_STRING,argsds);
            if (fread(buf,2,1,fp) == 0) goto fmterr; /* discard CRLF */
        }

        /* Command lookup */
        cmd = lookupCommand(argv[0]->ptr);

        /* Try object sharing and encoding */
        if (server.shareobjects) {
            int j;
            for(j = 1; j < argc; j++)
                argv[j] = tryObjectSharing(argv[j]);
        }
        if (cmd->flags & REDIS_CMD_BULK)
            tryObjectEncoding(argv[argc-1]);
        /* Run the command in the context of a fake client */
        fakeClient->argc = argc;
        fakeClient->argv = argv;
        cmd->proc(fakeClient);
        /* Discard the reply objects list from the fake client */
        while(listLength(fakeClient->reply))
            listDelNode(fakeClient->reply,listFirst(fakeClient->reply));
        /* Clean up, ready for the next command */
        for (j = 0; j < argc; j++) decrRefCount(argv[j]);
        zfree(argv);
        /* Handle swapping while loading big datasets when VM is on */
        loadedkeys++;
        if (server.vm_enabled && (loadedkeys % 5000) == 0) {
            while (zmalloc_used_memory() > server.vm_max_memory) {
                if (vmSwapOneObjectBlocking() == REDIS_ERR) break;
            }
        }
    }
    fclose(fp);
    freeFakeClient(fakeClient);
    return REDIS_OK;
}
//-----------------------------------------------------------------------------
static void load_paths_to_exclude(LPCTSTR path) {
//-----------------------------------------------------------------------------
    FILE * stream_p;
    wchar_t *get_result;
    size_t line_len;
    struct exclude_entry **link_p;
    struct exclude_entry * next_p;

    if (_wfopen_s(&stream_p, path, L"r, ccs=UTF-8")) {
        _wfopen_s(&error_file, error_path, L"w");
        _wcserror_s(error_buffer, sizeof error_buffer/sizeof(wchar_t), errno); 
        fwprintf(
            error_file, 
            L"_wfopen(%s) failed: (%d) %s\n",  
            path,
            errno,
            error_buffer 
        );
        fclose(error_file);
        ExitProcess(2);
    }

    link_p = &exclude_entry_list_p;
   
    while (1) {

        // create an exclude entry
        next_p = (struct exclude_entry *) HeapAlloc(
            GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(struct exclude_entry)
        );
		if (next_p == NULL){
			report_error(L"HeapAlloc failed to allocate memory", GetLastError());
			ExitProcess(203);
			}
        // read in the path to watch from config.txt
        get_result = \
            fgetws(full_file_name, ARRAYSIZE(full_file_name), stream_p);

        if (NULL == get_result) {
            if (0 == ferror(stream_p)) {
                HeapFree(GetProcessHeap(), 0, next_p);
                break;
            } 
            _wfopen_s(&error_file, error_path, L"w");
            _wcserror_s(
               error_buffer, sizeof error_buffer/sizeof(wchar_t) , errno
            ); 
            fwprintf(
                error_file, 
                L"fgetws(%s) failed: (%d) %s\n",  
                path,
                errno,
                error_buffer 
            );
            fclose(error_file);
            ExitProcess(2);
        }

        // clean out the newline, if there is one
        line_len = wcslen(full_file_name);
		if (line_len && full_file_name[line_len-1] == L'\n'){
			full_file_name[line_len-1] = L'\0';
			line_len--;
			}
        if (full_file_name[0] == L'\0')
           continue;
		next_p->dir_path_len = line_len;
		next_p->dir_path = (wchar_t *)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
			(line_len + 1) * sizeof(wchar_t));
		if (next_p->dir_path == NULL){
			report_error(L"HeapAlloc failed to allocate memory", GetLastError());
			ExitProcess(204);
		}
		wcsncpy_s(next_p->dir_path, line_len+1, full_file_name, line_len);
   
        // add this entry to the list
        *link_p = next_p;

        // point to the new entry's next pointer 
        link_p = &(*link_p)->next_p;
    } // while(1)

    fclose(stream_p);

} // load_paths_to_exclude
//-----------------------------------------------------------------------------
static void load_paths_to_watch(LPCTSTR path, HANDLE completion_port_h) {
//-----------------------------------------------------------------------------
    FILE * stream_p;
    wchar_t *get_result;
    HANDLE create_result;
    size_t line_len;
    struct watch_entry **link_p;
    struct watch_entry * next_p;

    if (_wfopen_s(&stream_p, path, L"r, ccs=UTF-8")) {
        _wfopen_s(&error_file, error_path, L"w");
        _wcserror_s(error_buffer, ARRAYSIZE(error_buffer), errno); 
        fwprintf(
            error_file, 
            L"_wfopen(%s) failed: (%d) %s\n",  
            path,
            errno,
            error_buffer 
        );
        fclose(error_file);
        ExitProcess(2);
    }

    link_p = &watch_entry_list_p;
   
    while (1) {

        // create a watch entry
        next_p = (struct watch_entry *) HeapAlloc(
            GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(struct watch_entry)
        );
		if (next_p == NULL){
			report_error(L"HeapAlloc failed to allocate memory", GetLastError());
			ExitProcess(200);
			}
        // read in the path to watch from config.txt
        get_result = \
            fgetws(full_file_name, ARRAYSIZE(full_file_name), stream_p);

        if (NULL == get_result) {
            if (0 == ferror(stream_p)) {
                HeapFree(GetProcessHeap(), 0, next_p);
                break;
            } 
            _wfopen_s(&error_file, error_path, L"w");
            _wcserror_s(
               error_buffer, sizeof error_buffer/sizeof(wchar_t) , errno
            ); 
            fwprintf(
                error_file, 
                L"fgetws(%s) failed: (%d) %s\n",  
                path,
                errno,
                error_buffer 
            );
            fclose(error_file);
            ExitProcess(2);
        }

        // clean out the newline, if there is one
        line_len = wcslen(full_file_name);
		if (line_len && full_file_name[line_len-1] == L'\n'){
			full_file_name[line_len-1] = L'\0';
			line_len--;
			}
        if (full_file_name[0] == L'\0')
           continue;
		next_p->dir_path_len = line_len;
		next_p->dir_path = (wchar_t *)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
			(line_len + 1) * sizeof(wchar_t));
		if (next_p->dir_path == NULL){
			report_error(L"HeapAlloc failed to allocate memory", GetLastError());
			ExitProcess(201);
		}
		wcsncpy_s(next_p->dir_path, line_len+1, full_file_name, line_len);
		next_p->changes_buffer = (BYTE *)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
			CHANGES_BUFFER_SIZE);
		if (next_p->changes_buffer == NULL){
			report_error(L"HeapAlloc failed to allocate memory", GetLastError());
			ExitProcess(202);
		}
        // 2020-09-05 dougfort -- we don't clean out trailing slash here
        // because if they are backing up something like c:\\, we need
        // the trailing slash. This will come back to bite us when we are
        // checking for excludes

        // open a file handle to watch the directory in overlapped mode
        next_p->hDirectory = CreateFile(
            next_p->dir_path,
            FILE_LIST_DIRECTORY,
            FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
            NULL,
            OPEN_EXISTING,
            FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED,
            NULL
        );

        // 2009-03-11 dougfort -- if we can't create this file, 
        // assume it is a top-level directory
        // which no longer exists; so ignore it and move on.
        if (INVALID_HANDLE_VALUE == next_p->hDirectory) {
            report_error(L"CreateFile", GetLastError());
            continue;
        }

        // add this file handle to the IO Complete port
        create_result = CreateIoCompletionPort(
            next_p->hDirectory,         // FileHandle,
            completion_port_h,          // ExistingCompletionPort,
            0,                          // CompletionKey,
            0                           // NumberOfConcurrentThreads
        );

        if (NULL == create_result) {
            report_error(L"CreateIOCompletionPort (add)", GetLastError());
            ExitProcess(102);
        }

        if (create_result != completion_port_h) {
            ExitProcess(103);
        }

        start_watch(next_p);

        // add this entry to the list
        *link_p = next_p;

        // point to the new entry's next pointer 
        link_p = &(*link_p)->next_p;
    } // while(1)

    fclose(stream_p);

} // load_paths_to_watch
Exemple #14
0
static int
mac_init_internal(int ignore_errors)
{
    const char *filename;
    char line[LINE_MAX];
    FILE *file;
    int error;

    error = 0;

    LIST_INIT(&label_default_head);

    if (!issetugid() && getenv("MAC_CONFFILE") != NULL)
        filename = getenv("MAC_CONFFILE");
    else
        filename = MAC_CONFFILE;
    file = fopen(filename, "re");
    if (file == NULL)
        return (0);

    while (fgets(line, LINE_MAX, file)) {
        char *comment, *parse, *statement;

        if (line[strlen(line)-1] == '\n')
            line[strlen(line)-1] = '\0';
        else {
            if (ignore_errors)
                continue;
            fclose(file);
            error = EINVAL;
            goto just_return;
        }

        /* Remove any comment. */
        comment = line;
        parse = strsep(&comment, "#");

        /* Blank lines OK. */
        statement = next_token(&parse);
        if (statement == NULL)
            continue;

        if (strcmp(statement, "default_labels") == 0) {
            char *name, *labels;

            name = next_token(&parse);
            labels = next_token(&parse);
            if (name == NULL || labels == NULL ||
                    next_token(&parse) != NULL) {
                if (ignore_errors)
                    continue;
                error = EINVAL;
                fclose(file);
                goto just_return;
            }

            if (mac_add_type(name, labels) == -1) {
                if (ignore_errors)
                    continue;
                fclose(file);
                goto just_return;
            }
        } else if (strcmp(statement, "default_ifnet_labels") == 0 ||
                   strcmp(statement, "default_file_labels") == 0 ||
                   strcmp(statement, "default_process_labels") == 0) {
            char *labels, *type;

            if (strcmp(statement, "default_ifnet_labels") == 0)
                type = "ifnet";
            else if (strcmp(statement, "default_file_labels") == 0)
                type = "file";
            else if (strcmp(statement, "default_process_labels") ==
                     0)
                type = "process";

            labels = next_token(&parse);
            if (labels == NULL || next_token(&parse) != NULL) {
                if (ignore_errors)
                    continue;
                error = EINVAL;
                fclose(file);
                goto just_return;
            }

            if (mac_add_type(type, labels) == -1) {
                if (ignore_errors)
                    continue;
                fclose(file);
                goto just_return;
            }
        } else {
            if (ignore_errors)
                continue;
            fclose(file);
            error = EINVAL;
            goto just_return;
        }
    }

    fclose(file);

    internal_initialized = 1;

just_return:
    if (error != 0)
        mac_destroy_internal();
    return (error);
}
main (int argc, char *argv[]) {  

  float PARMOD[10];
  PARMOD[0]= 0.0;
  PARMOD[1]= 0.0;
  PARMOD[2]= 0.0;
  PARMOD[3]=0.0;
  PARMOD[4]=0.0;
  PARMOD[5]=0.0;
  PARMOD[6]=0.0;
  
  int iopt;
  int i,j,k;
  float kp = 2.0;
  float ps = 0.0;
  float bxout,byout,bzout; // THESE NEED TO BE STORED IN MEMORY NOW
  // TIMESTEP LOOP STARTS HERE
  //int m;
  //for(m=0;m<=72;m++){
    // NEED TO CALCULATE Kp HERE
    
    // NEED TO COMPARE Kp RESULT TO iopt AND SET
    if(kp < 0.5){
      iopt = 1;
    }
    else if(kp > 0.5 && kp < 1.5){
      iopt = 2;
    }
    else if(kp > 1.5 && kp < 2.5){
      iopt = 3;
    }
    else if(kp > 2.5 && kp < 3.5){
      iopt = 4;
    }
    else if(kp > 3.5 && kp < 4.5){
      iopt = 5;
    }
    else if(kp > 4.5 && kp < 5.5){
      iopt = 6;
    }
    else if(kp > 5.5){
      iopt = 7;
    }

    // CREATE GRID AND STORE IN MEMORY
    int npoinx = 345, npoiny = 187, npoinz = 187;
    int xmin=-222, ymin=-47, zmin=ymin;
    int xmax=30, ymax=47, zmax=ymax;
    //float *xcord = new float[npoinx];
    float *xcord = malloc(npoinx * sizeof(float));
    xcord[0] = xmin;
    // X COORDINATES
    i = 0;
    while (xcord[i] < xmax){
    	i++;
        if(xcord[i-1] < -30. || xcord[i-1] >= 30.){ xcord[i] = xcord[i-1]+1.; }
        else if(xcord[i-1] < -8. || xcord[i-1] >= 8.){ xcord[i] = xcord[i-1]+0.5; }
        else if(xcord[i-1] <= 0. || xcord[i-1] >= 0.){ xcord[i] = xcord[i-1]+0.25; } 
    }
    i = 0;
    //float *ycord = new float[npoiny];
    float *ycord = malloc(npoiny * sizeof(float));
    ycord[0] = ymin;
    // Y COORDINATES
    while (ycord[i] < ymax){
    	i++;
        if(ycord[i-1] < -30. || ycord[i-1] >= 30.){ ycord[i] = ycord[i-1]+1.; }
        else if(ycord[i-1] < -8. || ycord[i-1] >= 8.){ ycord[i] = ycord[i-1]+0.5; }
        else if(ycord[i-1] <= 0. || ycord[i-1] >= 0.){ ycord[i] = ycord[i-1]+0.25; } 
    }
    i = 0;
    //float *zcord = new float[npoinz];
    float *zcord = malloc(npoinz * sizeof(float));
    zcord[0] = zmin;
    // Z COORDINATES
    while (zcord[i] < zmax){
    	i++;
        if(zcord[i-1] < -30. || zcord[i-1] >= 30.){ zcord[i] = zcord[i-1]+1.; }
        else if(zcord[i-1] < -8. || zcord[i-1] >= 8.){ zcord[i] = zcord[i-1]+0.5; }
        else if(zcord[i-1] <= 0. || zcord[i-1] >= 0.){ zcord[i] = zcord[i-1]+0.25; } 
    }
    
    // GRID LOOP STARTS HERE
    int l=0;
    float *bx = malloc(npoinx*npoiny*npoinz * sizeof(float));
    float *by = malloc(npoiny*npoiny*npoinz * sizeof(float));
    float *bz = malloc(npoinz*npoiny*npoinz * sizeof(float));
    for ( k = 0; k < npoinz; k++){
	    for ( j = 0; j < npoiny; j++){
		    for ( i = 0; i < npoinx; i++){
		        // EACH NEW GRID POINT PASS THROUGH THIS FUNCTION
			    t89c_(&iopt,PARMOD,&ps,&xcord[i],&ycord[j],&zcord[k],&bxout,&byout,&bzout);
			    bx[l] = bxout;
			    by[l] = byout;
			    bz[l] = bzout;
			    //printf("bx=%f,by=%f,bz=%f\n",bxout,byout,bzout);
			    //return 0;
			    l++;
		    }
	    }
    }
  //}
  
    // WRITE VTK FILE
    std::cout << "Starting VTK Write" << std::endl;
    resultfilename = "/home/bcurtis/Tsyganenko/output/";
	resultfilename.append("/Result");
	resultfilename.append(boost::lexical_cast<std::string>(m));
	resultfilename.append(".vtk");
	std::cout << "Result File Name is: " << resultfilename << std::endl;
	// SPRINTF??????
	
	// BINARY VTK FILE
	float val, val1, val2;
	FILE *myfile;
	myfile = fopen(resultfilename.c_str(),"w");
	fprintf(myfile, "# vtk DataFile Version 3.0\n");
	fprintf(myfile, "Brian's Data\nBINARY\n");
	fprintf(myfile, "DATASET RECTILINEAR_GRID\n");
	fprintf(myfile, "DIMENSIONS %d %d %d\n", npoinx, npoiny, npoinz);
	fprintf(myfile, "X_COORDINATES %d float\n", npoinx);
	for (i=0; i<npoinx; i++){
		val = FloatSwap(xcord[i]);
		fwrite((void *)&val, sizeof(float), 1, myfile);
	}
	fprintf(myfile, "\nY_COORDINATES %d float\n", npoiny);
	for (i=0; i<npoiny; i++){
		val = FloatSwap(ycord[i]);
		fwrite((void *)&val, sizeof(float), 1, myfile);
	}
	fprintf(myfile, "\nZ_COORDINATES %d float\n", npoinz);
	for (i=0; i<npoinz; i++){
		val = FloatSwap(zcord[i]);
		fwrite((void *)&val, sizeof(float), 1, myfile);
	}
	fprintf(myfile, "\nPOINT_DATA  %d\n", npoinx*npoiny*npoinz);
    fprintf(myfile, "\nSCALARS Bx FLOAT 1\n");
    fprintf(myfile, "LOOKUP_TABLE default\n");
    for (i=0; i<npoinx*npoiny*npoinz; i++){
      val = FloatSwap(bx[i]);
      fwrite((void *)&val, sizeof(float), 1, myfile);
    }
    fprintf(myfile, "\nSCALARS By FLOAT 1\n");
    fprintf(myfile, "LOOKUP_TABLE default\n");
    for (i=0; i<npoinx*npoiny*npoinz; i++){
      val = FloatSwap(by[i]);
      fwrite((void *)&val, sizeof(float), 1, myfile);
    }

    fprintf(myfile, "\nSCALARS Bz FLOAT 1\n");
    fprintf(myfile, "LOOKUP_TABLE default\n");
    for (i=0; i<npoinx*npoiny*npoinz; i++){
      val = FloatSwap(bz[i]);
      fwrite((void *)&val, sizeof(float), 1, myfile);
    }
	fclose(myfile);
	std::cout << "VTK Write Complete" << std::endl;
  
  free(xcord); free(bx);
  free(ycord); free(by);
  free(zcord); free(bz);
  return 1;

}
Exemple #16
0
int main(int argc,char **argv){
  int sockfd;
  char buffer[1024];
  struct sockaddr_in server_addr;
  struct hostent *host;
  int portnumber,nbytes;
  char host_addr[256];
  char host_file[256];
  char local_file[256];
  FILE *fp;
  char request[1024];
  int send,totalsend;
  int i;
  char *pt;
  if(argc!=2){
    fprintf(stderr,"Usage:%s web-address\a\n",argv[0]);
    exit (1);
  }
  printf("parameter.1 is: %s\n",argv[1]);
  ToLowerCase(argv[1]);
  printf("lowercase parameter.1 is: %s\n",argv[1]);
  GetHost(argv[1],host_addr,host_file,&portnumber);
  printf("webhost:%s\n",host_addr);
  printf("hostfile:%s\n",host_file);
  printf("portnumber:%d\n",portnumber);
  if((host=gethostbyname(host_addr))==NULL){
    fprintf(stderr,"Gethostname error,%s\n",strerror(errno));
    exit(1);
  }
  if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1){
  fprintf(stderr,"SOcket Error:%s\a\n",strerror(errno));
  exit(1);
}

  bzero(&server_addr,sizeof(server_addr));
  server_addr.sin_family=AF_INET;
  server_addr.sin_port=htons(portnumber);
  server_addr.sin_addr=*((struct in_addr *)host->h_addr);
	
  if(connect(sockfd,(struct sockaddr *)&server_addr,sizeof(struct sockaddr))==-1)
    {
      fprintf(stderr,"Connect Error:%s\a\n",strerror(errno));
      exit(1);
    }
  sprintf(request,"GET /%s HTTP/1.1\r\nAccept:*/*\r\nAccept-language:zh-cn\r\n User-Agent:Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)\r\n Host:%s:%d\r\nConnection:Close\r\n\r\n",host_file,host_addr,portnumber);
  if(host_file && *host_file)pt = Rstrchr(host_file,'/');
  else pt=0;
  memset(local_file,0,sizeof(local_file));
  if(pt && *pt){
    if((pt+1)&&*(pt+1))strcpy(local_file,pt+1);
    else memcpy(local_file,host_file,strlen(host_file)-1);
  }
  else if(host_file && *host_file)strcpy(local_file,host_file);
  else strcpy(local_file,"index.html");
  printf("local filename to write:%s\n\n",local_file);
  
  send=0;
  totalsend=0;
  nbytes=strlen(request);
  while(totalsend<nbytes){
    send=write(sockfd,request+totalsend,nbytes-totalsend);
    if(send==-1){
      printf("send error!%s\n",strerror(errno));
      exit(0);
    }
    totalsend+=send;
    printf("%d bytes send OK!\n",totalsend);
  }
  fp=fopen(local_file,"a");
  if(!fp){
    printf("create file error!%s\n",strerror(errno));
    return 0;
  }
  printf("\nThe following is the response header:\n");
  i=0;
  while((nbytes=read(sockfd,buffer,1))==1)
    if(i<4){
      if(buffer[0]=='\r'||buffer[0]=='\n')i++;
      else i=0;
      printf("%c",buffer[0]);
    }
    else {
      fwrite(buffer,1,1,fp);
      i++;
      if(i%1024==0)fflush(fp);
    }
  fclose(fp);
  close(sockfd);
  exit(0);
}
Exemple #17
0
struct Image *kodak_dc2x_get_picture (int picNum, int thumbnail) {

    int tfd, image_size, image_width, net_width, camera_header, components;
    Dc20Info *my_info;
    unsigned char color_thumb[14400];
    unsigned char pic[MAX_IMAGE_SIZE];
    struct pixmap	*pp;

    GdkImlibImage *this_image, *scaled_image;
    GdkImlibColorModifier mod;

    FILE *jpgfile;
    int jpgfile_size;
    char filename[1024];
    struct Image *im;

    if ((tfd = kodak_dc2x_open_camera()) == 0) {
        error_dialog("Could not open camera.");
        return (0);
    }

    my_info = get_info(tfd);

    fprintf(stderr, "downloading from a DC%x\n", my_info->model);

    if (my_info->model == 0x25) {
        fprintf(stderr, "Match with 25!\n");
        if (thumbnail) {
            fprintf(stderr, "Getting thumbnail #%d from a DC25!\n", picNum);
            if (get_thumb(tfd, picNum, color_thumb) == -1) {
                fprintf(stderr,"get_thumb failed!\n");
                return(0);
            } else {
                fprintf(stderr,"get_thumb returned ok! Creating ImLib image!\n");
                this_image = gdk_imlib_create_image_from_data(color_thumb, NULL, 80, 60);
                fprintf(stderr, "Made it back from imlib_create!\n");
                sprintf(filename, "%s/gphoto-kodak-%i.jpg", gphotoDir, picNum);
                gdk_imlib_save_image (this_image, filename, NULL);
                gdk_imlib_kill_image (this_image);
                jpgfile = fopen(filename, "r");
                fseek(jpgfile, 0, SEEK_END);
                jpgfile_size = ftell(jpgfile);
                rewind(jpgfile);
                im = (struct Image*)malloc(sizeof(struct Image));
                im->image = (char *)malloc(sizeof(char)*jpgfile_size);
                fread(im->image, (size_t)sizeof(char), (size_t)jpgfile_size, jpgfile);
                fclose(jpgfile);
                strcpy(im->image_type, "jpg");
                im->image_size = (int)jpgfile_size;
                im->image_info_size = 0;
                remove(filename);
                return (im);
            }
        } else {
            fprintf(stderr, "Getting picture #%d from a DC25!\n", picNum );
            if (get_pic(tfd, picNum, pic, 0) == -1) {
                fprintf(stderr, "get_pic puked!\n");
                return(0);
            } else {
                fprintf(stderr, "returned from get_pic ok!\n");

                /*
                 *	Setup image size with resolution
                 */

                image_size = IMAGE_SIZE(pic[4]);
                image_width = WIDTH(pic[4]);
                net_width = image_width - LEFT_MARGIN - RIGHT_MARGIN(pic[4]);
                camera_header = CAMERA_HEADER(pic[4]);
                components = 3;

                /*
                 *	Convert the image to 24 bits
                 */

                if ((pp = alloc_pixmap(net_width - 1, HEIGHT - BOTTOM_MARGIN - 1, components)) == NULL) {
                    if (!quiet) fprintf(stderr, "%s: convert_pic: error: alloc_pixmap\n", __progname);
                    return 0;
                }

                if (comet_to_pixmap(pic, pp) == -1) {
                    fprintf(stderr, "comet_to_pixmap puked!\n");
                    return (0);
                } else {

                    fprintf(stderr, "attempting to imlib_create the image!\n");
                    this_image = gdk_imlib_create_image_from_data(pp->planes, NULL, pp->width, pp->height);
                    fprintf(stderr, "Made it back from imlib_create!\n");

                    /* now we just need to resize it! */
                    if (!pic[4]) {
                        /* high res 493x373 */
                        fprintf(stderr, "High Res!\n");
                        scaled_image = gdk_imlib_clone_scaled_image(this_image, 493, 373);

                    } else {
                        /* low res 320x240 */
                        fprintf(stderr, "Low Res!\n");
                        scaled_image = gdk_imlib_clone_scaled_image(this_image, 320, 240);

                        /* How? */
                    }

                    gdk_imlib_kill_image(this_image);

                    /* correct the contrast a bit before handing it back.. */
                    gdk_imlib_get_image_modifier(scaled_image,&mod);
                    mod.contrast = 256 * 1.3;
                    gdk_imlib_set_image_modifier(scaled_image,&mod);
                    gdk_imlib_apply_modifiers_to_rgb(scaled_image);

                    kodak_dc2x_close_camera(tfd);

                    sprintf(filename, "%s/gphoto-kodak-%i.jpg", gphotoDir, picNum);
                    gdk_imlib_save_image (scaled_image, filename, NULL);
                    gdk_imlib_kill_image (scaled_image);
                    jpgfile = fopen(filename, "r");
                    fseek(jpgfile, 0, SEEK_END);
                    jpgfile_size = ftell(jpgfile);
                    rewind(jpgfile);
                    im = (struct Image*)malloc(sizeof(struct Image));
                    im->image = (char *)malloc(sizeof(char)*jpgfile_size);
                    fread(im->image,(size_t)sizeof(char),(size_t)jpgfile_size,jpgfile);
                    fclose(jpgfile);
                    strcpy(im->image_type, "jpg");
                    im->image_size = jpgfile_size;
                    im->image_info_size = 0;
                    remove(filename);

                    return (im);
                }

            }
        }
    } else {
        fprintf(stderr, "No match with 25!");
        return(0);
    }
    return(0);
}
Exemple #18
0
/* Initialization of neurons parameters */
int initialization(neuron **nrn, int numNeurons, int simTime)
{
    int i, j, idj, size=0;
    char *fname;
    double tmp;
    FILE *fp, *fq;

    srand (time(NULL));
        
    for(i = 0; i < numNeurons; ++i){
        (*nrn)[i].numPreSyn = 0;
        (*nrn)[i].E = 0.0;
        for(j = 0; j < simTime; ++j){
            (*nrn)[i].V[j] = randm(0.01, 0.1);
            (*nrn)[i].Z[j] = randm(0.01, 0.05);
            (*nrn)[i].S[j] = randm(0.01, 0.05);
            (*nrn)[i].N[j] = randm(0.01, 0.05);
        }
    }

    if(!(fp = fopen("stimuli.dat", "r"))){
        fname = "stimuli.dat";
        goto fail;
    }

    for(i = 0; i < numNeurons; ++i){
        for(j = 0; j < simTime; ++j){
            fscanf(fp, "%lf", &(*nrn)[i].Iext[j]);
        }
    }
    
    fclose(fp);

    if(!(fq = fopen("synapses.dat", "r"))){
        fname = "synapses.dat";
        goto fail;
    }

    for(i = 0; i < numNeurons; ++i){
        idj = 0;
        for(j = 0; j < numNeurons; ++j){
            fscanf(fp, "%lf", &tmp);
            if (tmp != 0){
                if (j == 0){
                    (*nrn)[i].W[0] = tmp;
                    (*nrn)[i].pre_id[0] = j;
                }else{
                    size++;
                    (*nrn)[i].W = (double *)realloc((*nrn)[i].W, size*sizeof(double));
                    (*nrn)[i].W[idj] = tmp;

                    (*nrn)[i].pre_id = (int *)realloc((*nrn)[i].pre_id,
                                size*sizeof(int));
                    (*nrn)[i].pre_id[idj] = j;
                    idj++;
                }
                (*nrn)[i].numPreSyn++;
            }
        }
    }

    fclose(fp);

    return 0;

fail:
    printf("File %s cannot be opened!\n", fname);
    exit(-1);
}
void CToolSetTileBlock::Load( const string& path )
{
	CTerrainMesh* pTerrain = CMapEditApp::GetInst()->GetTerrain();

	//////////////////////////////////////////////////////////////////////////
	string strFileName = path;
	locale loc;
	use_facet<ctype<TCHAR> >( loc ).tolower
		( &strFileName[0], &strFileName[strFileName.length()] );

	size_t npos = strFileName.rfind(".");
	if( npos != -1 )
		strFileName = strFileName.substr(0, npos);

	string strLastBlockName = strFileName + "_last.block";
	strFileName += ".block";

	FILE * fp = NULL;
	fp = fopen(strFileName.c_str(),"rb");
	if (! fp )
	{
		string log = strFileName + "阻挡文件无法打开,查看是否被删掉了";

		MessageBox(NULL,log.c_str(),"请换其他地图",MB_OK);
		return;
	}

	::CopyFile(strFileName.c_str(), strLastBlockName.c_str(), FALSE);

	//////////////////////////////////////////////////////////////////////////
	///version
	DWORD dwVersion = BLOCK_VERSION;
	fread(&dwVersion,sizeof(dwVersion),1,fp);

	switch (dwVersion)
	{
	case BLOCK_TEX_INFO:
		{
			///读取设置障纹理名
			int8 nBlockTpyeCnt = EBT_CNT - 1;
			int  nBlockTpye = -1;
			for ( int8 i = 0; i < nBlockTpyeCnt; ++i )
			{
				nBlockTpye = i + 1;
				size_t size = 0;

				fread(&size,sizeof(size),1,fp);
				if( size != 0 )
				{
					string name("");
					int nLen = 0;

					for ( size_t i = 0; i < size; ++i )
					{	
						fread(&nLen,sizeof(nLen),1,fp);
						name.resize(nLen);
						fread((TCHAR*)name.data(),nLen,1,fp);
					}
				
				}
			}
		}
	case BLOCK_VERSION:
		{
			//////////////////////////////////////////////////////////////////////////
			///grid
			int nGridCnt = pTerrain->GetGridCount();

			for ( int i  = 0; i < nGridCnt; ++i )
			{
				int nBlockType = 0;
				fread(&nBlockType,sizeof(nBlockType),1,fp);

				SGrid &grid = pTerrain->GetGrid(i);
				grid.nBlockType = nBlockType;
			}
			//////////////////////////////////////////////////////////////////////////
		}
	default:
		break;
	}

	fclose(fp);
}
Exemple #20
0
void run_pcie_logging(void)
{
    char dev_name[40];
    int pq_fd;
    unsigned int host_ring_buffer_size = RING_BUF_ELEMS * RING_BUF_ELEM_SIZE;
    volatile TrioMsg *p;

    printf("Waiting for PCIe logging data from card %d on queue %d...\n", 
           card_index, queue_index);

    if (path_prefix) {
        printf("PCIe logging into directory: '%s'\n", path_prefix);
        fflush(stdout);
    }

    /* Open the packet queue file. */
    snprintf(dev_name, sizeof(dev_name), "/dev/tilegxpci%d/packet_queue/t2h/%d",
             card_index, queue_index);
    do {
        pq_fd = open(dev_name, O_RDWR);
        if (pq_fd < 0) {
            sleep(1);
        }
    } while (pq_fd < 0);

    /* mmap the register space. */
    struct gxpci_host_pq_regs_app* pq_regs =
        (struct gxpci_host_pq_regs_app*)
        mmap(0, sizeof(struct gxpci_host_pq_regs_app),
             PROT_READ | PROT_WRITE,
             MAP_SHARED, pq_fd, TILEPCI_PACKET_QUEUE_INDICES_MMAP_OFFSET);
    if (pq_regs == MAP_FAILED) {
        fprintf(stderr, "Failed to mmap PCIe control registers.\n");
        exit(EXIT_FAILURE);
    }

    /* Configure and allocate the ring buffer for the receive queue. */
    tilepci_packet_queue_info_t buf_info;

    buf_info.buf_size = RING_BUF_ELEM_SIZE;

    int err = ioctl(pq_fd, TILEPCI_IOC_SET_PACKET_QUEUE_BUF, &buf_info);
    if (err < 0) {
        fprintf(stderr, "Failed TILEPCI_IOC_SET_PACKET_QUEUE_BUF: %s\n",
                strerror(errno));
        abort();
    }

    /* On the host side, mmap the receive queue region. */
    void* buffer =
        mmap(0, host_ring_buffer_size, PROT_READ | PROT_WRITE,
             MAP_SHARED, pq_fd, TILEPCI_PACKET_QUEUE_BUF_MMAP_OFFSET);
    assert(buffer != MAP_FAILED);

    /* On the host side, mmap the queue status. */
    struct tlr_pq_status *pq_status =
        mmap(0, sizeof(struct tlr_pq_status), PROT_READ | PROT_WRITE,
             MAP_SHARED, pq_fd, TILEPCI_PACKET_QUEUE_STS_MMAP_OFFSET);
    assert(pq_status != MAP_FAILED);

    pq_regs->consumer_index = 0;

    uint64_t packet_count = 0;
    volatile uint32_t write;
    uint32_t read = 0;

#ifdef CHECK_SEQ_NUM
    uint32_t expect_seq = 1;
#endif
    
#ifdef HOST_INTERRUPT_MODE
    volatile uint32_t* producer_index = &(pq_status->drv_consumer_index);
#else
    volatile uint32_t* producer_index = &(pq_regs->producer_index);
#endif

    volatile uint32_t* consumer_index = &(pq_regs->consumer_index);
    volatile enum gxpci_chan_status_t* status = &(pq_status->status);

    while (1) {
        if (*status == GXPCI_CHAN_RESET) {
            printf("Tile to Host PCIe logging channel was reset.\n");
            fflush(stdout);
            return;
        }

        // Get packets off the ring buffer by accessing the receive queue at
        // the new write index.
        write = *producer_index;

        while (write != read) {
            if (*status == GXPCI_CHAN_RESET) {
                printf("Tile to Host PCIe logging channel was reset.\n");
                fflush(stdout);
                return;
            }

            packet_count++;

            p = (TrioMsg *)(buffer + ((read&(RING_BUF_ELEMS-1))*RING_BUF_ELEM_SIZE));

            if (debug) {
                fprintf(stdout, "got a message\n");
                fprintf(stdout, "p->magic: %d\n", p->magic);
                fprintf(stdout, "p->fileno: %d\n", p->fileno);
#ifdef CHECK_SEQ_NUM
                fprintf(stdout, "p->seq: %d\n", p->seq);
#endif
                fprintf(stdout, "p->len: %d\n", p->len);
                fprintf(stdout, "p->next_offset: %d\n", p->next_offset);
                fprintf(stdout, "p->buf: ");
                fwrite(&p->buf, sizeof(char), p->len - offsetof(TrioMsg, buf), stdout);
                fprintf(stdout, "\n");
                fflush(stdout);
            }

#ifdef CHECK_SEQ_NUM
            if (p->seq != expect_seq) {
                /* Check for a reset before reporting a bad sequence
                 * number to prevent confusing users. */
                if (*status == GXPCI_CHAN_RESET) {
                    printf("Tile to Host PCIe logging channel was reset.\n");
                    fflush(stdout);
                    return;
                }
                fprintf(stderr, "BAD sequence expected %d got %d\n", expect_seq, p->seq);
                return;
            }
            expect_seq = p->seq + 1;
#endif

            switch (p->op) {
            case OP_OPEN:
                if (p->fileno < MAX_FDESC) {
                    fdesc[p->fileno] = malloc(sizeof(FDesc));
                    if (fdesc[p->fileno]) {
                        char mode[2];
                        mode[0] = p->buf[0];
                        mode[1] = '\0';
                        char *file_name = (char *)&p->buf[1];
                        if (path_prefix) {
                            /* Added path_prefix to the start of the
                             * file name. Added space for '\0' and '\'.
                             * By default, no prefix is added. */
                            int new_size = strlen(path_prefix) + strlen(file_name) + 1 + 1;
                            char *new_name = malloc(new_size);
                            if (!new_name) {
                                fprintf(stderr, "Failed to allocate memory for %s/%s\n",
                                        path_prefix, file_name);
                                return;
                            }
                            snprintf(new_name, new_size, "%s/%s", 
                                     path_prefix, file_name);
                            file_name = new_name;
                        }
                        if ((fdesc[p->fileno]->fd = fopen(file_name, mode)) == NULL) {
                            fprintf(stderr, "Could not open %s: %s\n",
                                    file_name, strerror(errno));
                        } else {
                            printf("Opened '%s' for logging.\n", file_name);
                            fflush(stdout);
                        }
                    }
                } else {
                    fprintf(stderr, "File number %d exceeds Max of %d\n", p->fileno, MAX_FDESC);
                }
                break;
            case OP_WRITE:
                if (drop_alerts) {
                    /* TODO: Report alert count periodically. */
                } else {
                    if (fdesc[p->fileno] && fdesc[p->fileno]->fd) {
                        fwrite(&p->buf, sizeof(char),
                               p->len - offsetof(TrioMsg, buf),
                               fdesc[p->fileno]->fd);
                        fflush(fdesc[p->fileno]->fd);
                    }
                }
                break;
            case OP_CLOSE:
                if (fdesc[p->fileno] && fdesc[p->fileno]->fd) {
                    fclose( fdesc[p->fileno]->fd);
                    free(fdesc[p->fileno]);
                    fdesc[p->fileno] = NULL;
                }
                break;
            }

            read++;
            /* Update the read index register to inform the tile side
             * that the packet has been read. */

#ifdef TAIL_UPDATE_LIMIT_ENABLE
            if ((packet_count & 0x3f) == 0)
                *consumer_index = read;
#else
            *consumer_index = read;
#endif
        }
    }
    return;
}
static CURLcode file_upload(struct connectdata *conn)
{
  struct FILEPROTO *file = conn->data->state.proto.file;
  const char *dir = strchr(file->path, DIRSEP);
  FILE *fp;
  CURLcode res=CURLE_OK;
  struct SessionHandle *data = conn->data;
  char *buf = data->state.buffer;
  size_t nread;
  size_t nwrite;
  curl_off_t bytecount = 0;
  struct timeval now = Curl_tvnow();
  struct_stat file_stat;
  const char* buf2;

  /*
   * Since FILE: doesn't do the full init, we need to provide some extra
   * assignments here.
   */
  conn->fread_func = data->set.fread_func;
  conn->fread_in = data->set.in;
  conn->data->req.upload_fromhere = buf;

  if(!dir)
    return CURLE_FILE_COULDNT_READ_FILE; /* fix: better error code */

  if(!dir[1])
     return CURLE_FILE_COULDNT_READ_FILE; /* fix: better error code */

  if(data->state.resume_from)
    fp = fopen( file->path, "ab" );
  else {
    int fd;

#ifdef DOS_FILESYSTEM
    fd = open(file->path, O_WRONLY|O_CREAT|O_TRUNC|O_BINARY,
              conn->data->set.new_file_perms);
#else
    fd = open(file->path, O_WRONLY|O_CREAT|O_TRUNC,
              conn->data->set.new_file_perms);
#endif
    if(fd < 0) {
      failf(data, "Can't open %s for writing", file->path);
      return CURLE_WRITE_ERROR;
    }
    close(fd);
    fp = fopen(file->path, "wb");
  }

  if(!fp) {
    failf(data, "Can't open %s for writing", file->path);
    return CURLE_WRITE_ERROR;
  }

  if(-1 != data->set.infilesize)
    /* known size of data to "upload" */
    Curl_pgrsSetUploadSize(data, data->set.infilesize);

  /* treat the negative resume offset value as the case of "-" */
  if(data->state.resume_from < 0) {
    if(fstat(fileno(fp), &file_stat)) {
      fclose(fp);
      failf(data, "Can't get the size of %s", file->path);
      return CURLE_WRITE_ERROR;
    }
    else
      data->state.resume_from = (curl_off_t)file_stat.st_size;
  }

  while(res == CURLE_OK) {
    int readcount;
    res = Curl_fillreadbuffer(conn, BUFSIZE, &readcount);
    if(res)
      break;

    if(readcount <= 0)  /* fix questionable compare error. curlvms */
      break;

    nread = (size_t)readcount;

    /*skip bytes before resume point*/
    if(data->state.resume_from) {
      if((curl_off_t)nread <= data->state.resume_from ) {
        data->state.resume_from -= nread;
        nread = 0;
        buf2 = buf;
      }
      else {
        buf2 = buf + data->state.resume_from;
        nread -= (size_t)data->state.resume_from;
        data->state.resume_from = 0;
      }
    }
    else
      buf2 = buf;

    /* write the data to the target */
    nwrite = fwrite(buf2, 1, nread, fp);
    if(nwrite != nread) {
      res = CURLE_SEND_ERROR;
      break;
    }

    bytecount += nread;

    Curl_pgrsSetUploadCounter(data, bytecount);

    if(Curl_pgrsUpdate(conn))
      res = CURLE_ABORTED_BY_CALLBACK;
    else
      res = Curl_speedcheck(data, now);
  }
  if(!res && Curl_pgrsUpdate(conn))
    res = CURLE_ABORTED_BY_CALLBACK;

  fclose(fp);

  return res;
}
int read_A_b_from_file(const char *infile, int *nnodes, int *nnz, int **ia, int **ja,  int **iau, double **A, double **rhs, int neqs)
{
    //local vars
    int i = 0, j = 0, l = 0, m = 0;
    int jstart, jend;
    FILE *fid = NULL;
    const int str_dim = 500;
    char str[str_dim];

    //openning the file
    if( (fid = fopen(infile, "r")) == NULL)
    {
        printf ("\ncouldn't read from input file. Error occured at file = %s, line %d. Proceeding to exit ...\n",__FILE__, __LINE__);
        fflush(stdout);
        exit(0);
    }

    //starting to read
    fgets(str,str_dim,fid); //skip that line
    fscanf(fid,"%d\n",nnodes); //number of nodes
    printf("\n nnodes = %d", *nnodes);
    fgets(str,str_dim,fid); //skip that line
    fscanf(fid,"%d\n",nnz); //number of entries
    printf("\n nnz = %d", *nnz);
    //allocating required arrays
    //THESE WILL BE RETURNED BACK
    (*ia) = (int *)malloc( (*nnodes + 1) * sizeof(int) );
    (*iau) = (int *)malloc( (*nnodes) * sizeof(int) );
    (*ja) = (int *)malloc( (*nnz) * sizeof(int) );
    (*A) = (double *)malloc( neqs * neqs * (*nnz) * sizeof(double) );
    (*rhs) = (double *)malloc( neqs * (*nnodes) * sizeof(double) );

    fgets(str,str_dim,fid); //skip that line
    //reading ia
    for(i = 0; i < (*nnodes + 1); i++)
    {
        fscanf(fid,"%d\n",(*ia + i));
        (*ia)[i]--; //resetting zero-based!
    }
    printf("\n ia[end] = %d", (*ia)[*nnodes]);
    fgets(str,str_dim,fid); //skip that line
    //reading iau
    for(i = 0; i < (*nnodes) ; i++)
    {
        fscanf(fid,"%d\n",(*iau + i));
        (*iau)[i]--; //resetting zero-based!
    }
    printf("\n iau[end] = %d", (*iau)[*nnodes-1]);
    fgets(str,str_dim,fid); //skip that line
    //reading ja
    for(i = 0; i < (*nnz) ; i++)
    {
        fscanf(fid,"%d\n",(*ja + i));
        (*ja)[i]--; //resetting zero-based!
    }
    printf("\n ja[end] = %d", (*ja)[*nnz-1]);
    //reading sparse matrix [A]
    fgets(str,str_dim,fid); //skip that line
    for( i = 0; i < (*nnodes); i++)
    {
        jstart = (*ia)[i];
        jend =  (*ia)[i+1] - 1;
        for (j = jstart; j <= jend; j++)
            for(l = 0; l < neqs; l++)
            {
                for(m = 0; m < (neqs-1); m++)
                    fscanf(fid,"%lf ", (*A + j* neqs * neqs+ l * neqs + m));
                fscanf(fid,"%lf\n", (*A + j* neqs * neqs+ l * neqs + m));
            }
    }
    printf("\n A[end,end,end] = %1.16f", *(*A + (j-1)* neqs * neqs+ (l-1) * neqs + m));
    fgets(str,str_dim,fid); //skip that line
    for( i = 0; i < (*nnodes); i++)
    {

        for( m = 0; m < (neqs-1); m++)
            fscanf(fid,"%lf ",(*rhs + i* neqs + m));

        fscanf(fid,"%lf\n", (*rhs + i* neqs + m));
    }
    printf("\n rhs[end,end] = %1.16f", *(*rhs + (i-1)* neqs + m));

    //closing the input file
    fclose(fid);

    printf("\nMatrices A and rhs were ported successfully!\n");

    //completed successfully!
    return 0;
}
bool ObjectTemplateCustomizationDataWriter::writeToFile(const std::string &pathName, bool allowOverwrite)
{
	//-- Don't write anything if there's no data to write.
	bool hasData = false;

	if (!m_paletteColorData->empty())
		hasData = true;

	if (!m_rangedIntData->empty())
		hasData = true;

	if (!hasData)
	{
		DEBUG_REPORT_LOG(true, ("writeToFile(): no data: skipped writing [%s].\n", pathName.c_str()));
		return true;
	}

	//-- Handle no-overwrite case.
	if (!allowOverwrite)
	{
		FILE *const testFile = fopen(pathName.c_str(), "r");
		if (testFile != NULL)
		{
			fclose(testFile);
			DEBUG_REPORT_LOG(true, ("writeToFile(): overwrite attempt: skipped writing [%s] because it already exists and allowOverwrite == false.\n", pathName.c_str()));
			return false;
		}
	}

	//-- open file
	FILE *const file = fopen(pathName.c_str(), "w");
	if (!file)
	{
		WARNING(true, ("failed to create file [%s].", pathName.c_str()));
		return false;
	}

	//-- sort the output data
	m_paletteColorData->sort();
	m_rangedIntData->sort();

	//-- write palette color variables
	fprintf(file, "paletteColorCustomizationVariables = [");
	{
		int i = 0;
		int const count = static_cast<int>(m_paletteColorData->size());

		const StringList::iterator endIt = m_paletteColorData->end();
		for (StringList::iterator it = m_paletteColorData->begin(); it != endIt; ++it, ++i)
		{
			if (i == (count - 1))
			{
				// -- Fixup last entry to use ] in place of final comma.
				std::string::size_type position = it->rfind(',');
				DEBUG_FATAL(static_cast<int>(position) == static_cast<int>(std::string::npos), ("bad data, where's the final comma?"));

				(*it)[position] = ']';
			}

			fprintf(file, "\n  %s", it->c_str());
		}
	}
	if (m_paletteColorData->empty())
		fprintf(file, "]");
	fprintf(file, "\n\n");

	//-- write ranged int variables
	fprintf(file, "rangedIntCustomizationVariables = [");
	{
		int i = 0;
		int const count = static_cast<int>(m_rangedIntData->size());

		const StringList::iterator endIt = m_rangedIntData->end();
		for (StringList::iterator it = m_rangedIntData->begin(); it != endIt; ++it, ++i)
		{
			if (i == (count - 1))
			{
				// -- Fixup last entry to use ] in place of final comma.
				std::string::size_type position = it->rfind(',');
				DEBUG_FATAL(static_cast<int>(position) == static_cast<int>(std::string::npos), ("bad data, where's the final comma?"));

				(*it)[position] = ']';
			}

			fprintf(file, "\n  %s", it->c_str());
		}
	}
	if (m_rangedIntData->empty())
		fprintf(file, "]");
	fprintf(file, "\n\n");

	fclose(file);

	//-- return success
	return true;
}
Exemple #24
0
void localLeapFrogAccuracy(){
	double h = 1;
	int n = 3;
	particle * particles = malloc(n * sizeof(particle));
	FILE * fp;
	double currentEnergy;
	double energyChange;
	double energy;
	
	fp = fopen("lin3local1.dat","w");
	initialize_linearx(particles, n);
	energy = totalEnergy(particles, n);
	
	printf("initial energy = %g\n", energy);
	leapFrogStep(particles, n, 0.01);
	currentEnergy = totalEnergy(particles, n);
	printf("current energy = %g\n", currentEnergy);
	fprintParticles(stdout, particles, n);
	
	for (h = 1;h>1E-8;h/=2){
		initialize_linearx(particles, n);
		leapFrogStep(particles, n, h);
		currentEnergy = totalEnergy(particles, n);
		energyChange = fabs(currentEnergy - energy);
		fprintf(fp, "%g\t%g\n", h, energyChange);
	}
	fclose(fp);
	
	// 

	fp = fopen("lin3local10.dat","w");
	initialize_linearx(particles, n);
	energy = totalEnergy(particles, n);
	for (h = 1;h>1E-8;h/=2){
		initialize_linearx(particles, n);
		leapFrogStep(particles, n, h);
		leapFrogStep(particles, n, h);
		leapFrogStep(particles, n, h);
		leapFrogStep(particles, n, h);
		leapFrogStep(particles, n, h);
		leapFrogStep(particles, n, h);
		leapFrogStep(particles, n, h);
		leapFrogStep(particles, n, h);
		leapFrogStep(particles, n, h);
		leapFrogStep(particles, n, h);
		currentEnergy = totalEnergy(particles, n);
		energyChange = fabs(currentEnergy - energy);
		fprintf(fp, "%g\t%g\n", h, energyChange);
	}
	fclose(fp);
	
	//	10 particles
	free(particles);
	n = 10;
	particles = malloc(n * sizeof(particle));
	
	fp = fopen("lin10local1.dat","w");
	initialize_linearx(particles, n);
	energy = totalEnergy(particles, n);
	for (h = 1;h>1E-8;h/=2){
		initialize_linearx(particles, n);
		leapFrogStep(particles, n, h);
		currentEnergy = totalEnergy(particles, n);
		energyChange = fabs(currentEnergy - energy);
		fprintf(fp, "%g\t%g\n", h, energyChange);
	}
	fclose(fp);
	
	// 

	fp = fopen("lin10local10.dat","w");
	initialize_linearx(particles, n);
	energy = totalEnergy(particles, n);
	for (h = 1;h>1E-8;h/=2){
		initialize_linearx(particles, n);
		leapFrogStep(particles, n, h);
		leapFrogStep(particles, n, h);
		leapFrogStep(particles, n, h);
		leapFrogStep(particles, n, h);
		leapFrogStep(particles, n, h);
		leapFrogStep(particles, n, h);
		leapFrogStep(particles, n, h);
		leapFrogStep(particles, n, h);
		leapFrogStep(particles, n, h);
		leapFrogStep(particles, n, h);
		currentEnergy = totalEnergy(particles, n);
		energyChange = fabs(currentEnergy - energy);
		fprintf(fp, "%g\t%g\n", h, energyChange);
	}
	fclose(fp);
	
	
	
	
	free(particles);
}
int wf1_get_data (const char *fname, DATASET *dset,
		  gretlopt opt, PRN *prn)
{
    FILE *fp;
    DATASET *newset = NULL;
    unsigned offset;
    int nvread, ftype;
    int err = 0;

    fp = gretl_fopen(fname, "rb");
    if (fp == NULL) {
	return E_FOPEN;
    }

    ftype = wf1_check_file_type(fp);
    
    if (ftype < 0) {
	fclose(fp);
	pputs(prn, "This file does not seem to be an EViews workfile\n");
	return E_DATA;
    }

    if (ftype == 1) {
	pputs(prn, "EViews 7+ file: expect problems!\n");
    }

    newset = datainfo_new();
    if (newset == NULL) {
	pputs(prn, _("Out of memory\n"));
	fclose(fp);
	return E_ALLOC;
    }

    err = parse_wf1_header(fp, ftype, newset, &offset);
    if (err) {
	pputs(prn, _("Error reading workfile header\n"));
	free_datainfo(newset);
	fclose(fp);
	return err;
    }

    err = start_new_Z(newset, 0);
    if (err) {
	pputs(prn, _("Out of memory\n"));
	free_datainfo(newset);
	fclose(fp);
	return E_ALLOC;
    }	

    err = read_wf1_variables(fp, ftype, offset, newset, &nvread, prn);

    if (err) {
	destroy_dataset(newset);
    } else {
	int merge = (dset->Z != NULL);
	int nvtarg = newset->v - 1;

	if (nvread < nvtarg) {
	    dataset_drop_last_variables(newset, nvtarg - nvread);
	}

	if (fix_varname_duplicates(newset)) {
	    pputs(prn, _("warning: some variable names were duplicated\n"));
	}

	err = merge_or_replace_data(dset, &newset, opt, prn);

	if (!err && !merge) {
	    dataset_add_import_info(dset, fname, GRETL_WF1);
	}
    }

    fclose(fp);

    return err;
}  
Exemple #26
0
void globalLeapFrogAccuracy(){
	double h = 1;
	int n = 3;
	double t;
	FILE * fp;
	particle * particles = malloc(n * sizeof(particle));
	double energy;
	double currentEnergy;
	double energyChange;
	
	//lin3 global
	fp = fopen("lin3global.dat","w");
	initialize_linearx(particles, n);
	energy = totalEnergy(particles, n);
	for (h = 0.1;h>1E-7;h*=0.5){
		initialize_linearx(particles, n);
		for(t=0;t<0.1;t+=h){
			//printf("leapfrogging at time t = %lf", t);
			leapFrogStep(particles, n, h);
		}
		currentEnergy = totalEnergy(particles, n);
		energyChange = fabs(currentEnergy - energy);
		fprintf(fp, "%g\t%g\n", h, energyChange);
	}
	fclose(fp);
	
	
	//equilateral global
	fp = fopen("equilateralglobal.dat","w");
	initialize_equilateral(particles, n);
	energy = totalEnergy(particles, n);
	for (h = 0.1;h>1E-7;h*=0.5){
		initialize_equilateral(particles, n);
		for(t=0;t<0.1;t+=h){
			//printf("leapfrogging at time t = %lf", t);
			leapFrogStep(particles, n, h);
		}
		currentEnergy = totalEnergy(particles, n);
		energyChange = fabs(currentEnergy - energy);
		fprintf(fp, "%g\t%g\n", h, energyChange);
	}
	fclose(fp);
	
	
	printf("10 particles may take some time\n");
	//linear 10 global
	free(particles);
	n = 10;
	particles = malloc(n * sizeof(particle));
	fp = fopen("lin10global.dat","w");
	initialize_linearx(particles, n);
	energy = totalEnergy(particles, n);
	for (h = 0.1;h>1E-6;h*=0.5){
		initialize_linearx(particles, n);
		for(t=0;t<0.1;t+=h){
			//printf("leapfrogging at time t = %lf", t);
			leapFrogStep(particles, n, h);
		}
		currentEnergy = totalEnergy(particles, n);
		energyChange = fabs(currentEnergy - energy);
		fprintf(fp, "%g\t%g\n", h, energyChange);
	}
	fclose(fp);
	
	//random 10 global
	free(particles);
	n = 10;
	particles = malloc(n * sizeof(particle));
	fp = fopen("random10global.dat","w");
	initialize_2(particles, n);
	energy = totalEnergy(particles, n);
	for (h = 0.1;h>1E-6;h*=0.5){
		initialize_2(particles, n);
		for(t=0;t<0.1;t+=h){
			//printf("leapfrogging at time t = %lf", t);
			leapFrogStep(particles, n, h);
		}
		currentEnergy = totalEnergy(particles, n);
		energyChange = fabs(currentEnergy - energy);
		fprintf(fp, "%g\t%g\n", h, energyChange);
	}
	fclose(fp);
	
	
	printf("20 particles may take noticeably more time\n");
	//random 20 global
	free(particles);
	n = 20;
	particles = malloc(n * sizeof(particle));
	fp = fopen("random20global.dat","w");
	initialize_3(particles, n);
	//fprintParticles(stdout, particles, n);
	energy = totalEnergy(particles, n);
	for (h = 0.1;h>1E-6;h*=0.5){
		initialize_3(particles, n);
		for(t=0;t<0.1;t+=h){
			//printf("leapfrogging at time t = %lf", t);
			leapFrogStep(particles, n, h);
		}
		currentEnergy = totalEnergy(particles, n);
		energyChange = fabs(currentEnergy - energy);
		fprintf(fp, "%g\t%g\n", h, energyChange);
	}
	fclose(fp);
	
	printf("40 particles may take noticeably more time\n");
	//random 40 global
	free(particles);
	n = 40;
	particles = malloc(n * sizeof(particle));
	fp = fopen("random40global.dat","w");
	initialize_3(particles, n);
	//fprintParticles(stdout, particles, n);
	energy = totalEnergy(particles, n);
	for (h = 0.1;h>1E-6;h*=0.5){
		initialize_3(particles, n);
		for(t=0;t<0.1;t+=h){
			//printf("leapfrogging at time t = %lf", t);
			leapFrogStep(particles, n, h);
		}
		currentEnergy = totalEnergy(particles, n);
		energyChange = fabs(currentEnergy - energy);
		fprintf(fp, "%g\t%g\n", h, energyChange);
	}
	fclose(fp);
	
	free(particles);
}
Exemple #27
0
VOID ImportFilesBBS ()
{
   FILE *fp;
   USHORT PendingWrite;
   ULONG Total;
   CHAR Path[128], Temp[128], *p, *Name;
   struct stat statbuf;
   struct tm *ltm;
   class TFileData *Data;
   class TFileBase *File;

   printf (" * Import from FILES.BBS\r\n");

   unlink ("filebase.dat");
   unlink ("filebase.idx");

   if ((Data = new TFileData (Cfg->SystemPath)) != NULL) {
      if (Data->First () == TRUE)
         do {
            PendingWrite = FALSE;
            Total = 0L;
            printf (" +-- %-15.15s %-45.45s ", Data->Key, Data->Display);
            if ((File = new TFileBase (Cfg->SystemPath, Data->Key)) != NULL) {
               sprintf (Path, "%sfiles.bbs", Data->Download);
               if ((fp = fopen (Path, "rt")) != NULL) {
                  while (fgets (Temp, sizeof (Temp) - 1, fp) != NULL) {
                     if ((p = strchr (Temp, 0x0A)) != NULL)
                        *p = '\0';
                     if (Temp[0] != ' ' && Temp[0] != 0x09) {
                        if (PendingWrite == TRUE) {
                           File->Add ();
                           Total++;
                           File->Clear ();
                           PendingWrite = FALSE;
                        }
                        if ((Name = strtok (Temp, " ")) != NULL) {
                           if ((p = strtok (NULL, "")) != NULL) {
                              while (*p == ' ')
                                 p++;
                              if (*p == '(' || *p == '[') {
                                 while (*p != ')' && *p != ']' && *p != '\0') {
                                    if (isdigit (*p)) {
                                       File->DlTimes *= 10;
                                       File->DlTimes += *p - '0';
                                    }
                                    p++;
                                 }
                                 if (*p == ')' || *p == ']') {
                                    p++;
                                    while (*p == ' ')
                                       p++;
                                 }
                              }
                              if (*p != '\0')
                                 File->Description->Add (p, (USHORT)(strlen (p) + 1));
                           }
                           sprintf (Path, "%s%s", Data->Download, Name);
#if defined(__LINUX__)
                           strlwr (Path);
#endif
                           if (!stat (Path, &statbuf)) {
                              strcpy (File->Area, Data->Key);
                              strcpy (File->Name, Name);
                              sprintf (File->Complete, "%s%s", Data->Download, Name);
                              File->Size = statbuf.st_size;
                              ltm = localtime ((time_t *)&statbuf.st_mtime);
                              File->UplDate.Day = File->Date.Day = (UCHAR)ltm->tm_mday;
                              File->UplDate.Month = File->Date.Month = (UCHAR)(ltm->tm_mon + 1);
                              File->UplDate.Year = File->Date.Year = (USHORT)(ltm->tm_year + 1900);
                              File->UplDate.Hour = File->Date.Hour = (UCHAR)ltm->tm_hour;
                              File->UplDate.Minute = File->Date.Minute = (UCHAR)ltm->tm_min;
                              File->Uploader = "Sysop";
                              File->CdRom = Data->CdRom;
                              PendingWrite = TRUE;
                           }
                           else
                              File->Clear ();
                        }
                     }
                     else if (PendingWrite == TRUE) {
                        p = Temp;
                        while (*p == ' ' || *p == 0x09)
                           p++;
                        if (*p == '>' || *p == '|' || *p == '+') {
                           p++;
                           File->Description->Add (p);
                        }
                     }
                  }
                  fclose (fp);

                  if (PendingWrite == TRUE) {
                     File->Add ();
                     File->Clear ();
                     Total++;
                     PendingWrite = FALSE;
                  }
               }
               else
                  printf ("Error\r\n");

               File->Close ();
               delete File;

               Data->ActiveFiles = Total;
               Data->Update ();
            }
            printf ("Total: %5lu\r\n", Total);
         } while (Data->Next () == TRUE);
      delete Data;
   }
}
Exemple #28
0
uint32_t direct_writeblock(const char *src_path, uint64_t chunkid, uint64_t *t_size)
{
	uint8_t *ptr = NULL;
	uint8_t *ibuff = NULL;
	int8_t status = 0;
	uint64_t size;
	uint64_t len;
	uint32_t read_size = 0;
	FILE *fp = NULL;
	char *p_data = NULL;

    fp = fopen(src_path, "rb");
    if (fp == NULL) {
        fprintf(stderr, "open file(%s) failed!\n", src_path);
        return 3;
    }

    size = get_file_size(src_path);
    if (size <= 0) { // 大小为0的文件丢弃
        fprintf(stderr, "get file(%s) error!\n", src_path);
		fclose(fp);
        return 3;
    }
 
	ibuff = malloc(24);
	ptr = ibuff;

	PUT32BIT(DRWTODAT_WRITE_INFO, ptr);
	PUT32BIT(16, ptr);
	PUT64BIT(chunkid, ptr);
	PUT64BIT(size,ptr);

	if (tcptowrite(rw_sock, ibuff, 24, CSMSECTIMEOUT) != 24) {
		free(ibuff);
		fclose(fp);
		fprintf(stderr, "write data to dat error!\n");
		return 3;
	}
	free(ibuff);
	// 等待dat端的回复
	uint8_t hdr[13];
	uint8_t *ptr1 = NULL;
	uint32_t cmd1 = 0;
	uint32_t len1 = 0;
	uint32_t version1 = 0;

	ptr1 = hdr;
	if (read(rw_sock, hdr, 13) != 13) {
		fprintf(stderr, "read data from dat error\n");
	}
	GET32BIT(cmd1, ptr1);
	GET32BIT(len1, ptr1);
	GET32BIT(version1, ptr1);
	GET8BIT(status, ptr1);
int i = 0;
for(i=0; i< 13; i++) {
	fprintf(stderr, "%u-", hdr[i]);
}
fprintf(stderr, "hdr end\n");


	if (cmd1 != DATTODRW_WRITE_INFO || status != 0) {
		fprintf(stderr, "dat not ready!\n");
		return 1;
	} 

	ibuff = malloc(W_PACK_SIZE*sizeof(uint8_t));
	ptr = ibuff;
	p_data = malloc(W_PACK_SIZE*sizeof(char));
	len = 0;
  	while (len < size) {
        read_size = fread(p_data, sizeof(char), W_PACK_SIZE, fp);
	 	if (read_size < 0) {
            fprintf(stderr, "fread file(%s) error!\n", src_path);
		 	fclose(fp);
			free(ibuff);
			free(p_data);
            return 3;
        }
		memcpy(ptr, p_data, read_size);
		if (tcptowrite(rw_sock, ibuff, read_size, CSMSECTIMEOUT) != read_size) {
			fprintf(stderr, "readblock; tcpwrite error!\n");
			free(ibuff);
			free(p_data);
		 	fclose(fp);
			return 3;
		}
		if (DEBUG) {
			fprintf(stderr, "total size(%llu), read size: %llu\n",
					(unsigned long long int)size, (unsigned long long int)len);
		}
		len += read_size;
	}
	fprintf(stderr, "Write over!\n");
	
	*t_size = size;
    fclose(fp);
	free(ibuff);
	free(p_data);

	return status;
}
Exemple #29
0
static char *scpi_handle_profile(struct osc_plugin *plugin, const char *attrib,
		const char *value)
{
	gchar **elems, **min_max;
	char *buf;
	int i;
	double lvl;
	long long j;
	FILE *fd;

	if (value)
		buf = NULL;
	else {
		buf = malloc(128);
		memset(buf, 0, 128);
	}

	current_instrument = NULL;

	elems = g_strsplit(attrib, ".", 0);
	if (!strncmp(elems[0], "rx", 2))
		current_instrument = &spectrum_analyzer;
	if (!strncmp(elems[0], "tx", 2))
		current_instrument = &signal_generator;

	if (!current_instrument)
		return NULL;

	if (strcmp(elems[1], SERIAL_TOK) == 0) {
		if (value) {
			if (atoi(value) == 1)
				current_instrument->serial = TRUE;
		} else {
			if (current_instrument->serial)
				sprintf(buf, "1");
		}
	} else if (strcmp(elems[1], NET_TOK) == 0) {
		if (value) {
			if (atoi(value) == 1)
				current_instrument->network = TRUE;
		} else {
			if (current_instrument->network)
				sprintf(buf, "1");
		}
	} else if (strcmp(elems[1], REGEX_TOK) == 0) {
		if (value) {
			current_instrument->id_regex = strdup(value);
		} else {
			if (current_instrument->id_regex)
				sprintf(buf, "%s", current_instrument->id_regex);
		}
	} else if (strcmp(elems[1], IP_TOK) == 0) {
		if (value) {
			current_instrument->ip_address = strdup(value);
		} else {
			if (current_instrument->ip_address && current_instrument->network)
				sprintf(buf, "%s", current_instrument->ip_address);
		}
	} else if (strcmp(elems[1], TTY_TOK) == 0) {
		if (value) {
			current_instrument->tty_path = strdup(value);
		} else {
			if (current_instrument->tty_path && current_instrument->serial)
				sprintf(buf, "%s", current_instrument->tty_path);
		}
	} else if (strcmp(elems[1], GPIB_TOK) == 0) {
		if (value) {
			current_instrument->gpib_addr = atoi(value);
		} else {
			if (current_instrument->gpib_addr && current_instrument->serial)
				sprintf(buf, "%i", current_instrument->gpib_addr);
		}
	} else
	/* There are some things testers need to add by hand to do things */
	if (strcmp(elems[1], CON_TOK) == 0) {
		if (value) {
			if (atoi(value) == 1)
				if (scpi_connect(current_instrument) != 0)
					return "FAIL";
		}
		/* We don't save the connect state */
	} else if (MATCH_ATTRIB("tx.freq")) {
		if (value)
			tx_freq_set_Hz(&signal_generator, atoll(value));
		/* We don't save the frequency */
	} else if (MATCH_ATTRIB("tx.mag")) {
		if (value)
			tx_mag_set_dBm(&signal_generator, atof(value));
		/* Don't save the magintude */
	} else if (MATCH_ATTRIB("tx.on")) {
		if (value)
			tx_output_set(&signal_generator, atoi(value));
		/* Don't save the on/off state */
	} else if (MATCH_ATTRIB("rx.setup")) {
		if (value)
			scpi_rx_setup(&spectrum_analyzer);
	} else if (MATCH_ATTRIB("rx.center")) {
		if (value)
			scpi_rx_set_center_frequency(atoll(value));
	} else if (MATCH_ATTRIB("rx.span")) {
		if (value)
			scpi_rx_set_span_frequency(atoll(value));
	} else if (!strncmp(attrib, "rx.marker", strlen("rx.marker"))) {
		if (value) {
			i = atoi(&attrib[strlen("rx.marker")]);
			j = atoll(value);
			if (i && j)
				scpi_rx_set_marker_freq(i, j);
			else
				printf("problems with %s = %s\n", attrib, value);
		}
	} else if (!strncmp(attrib, "rx.log.marker", strlen("rx.log.marker"))) {
		if (value) {
			i = atoi(&attrib[strlen("rx.log.marker")]);
			if (i) {
				scpi_rx_get_marker_level(i, true, &lvl);
				fd = fopen(value, "a");
				if (!fd)
					return NULL;

				fprintf (fd, "%f, ", lvl);
				fclose (fd);
			}
		}
	} else if (!strncmp(attrib, "rx.test.marker", strlen("rx.test.marker"))) {
		if (value) {
			i = atoi(&attrib[strlen("rx.test.marker")]);
			if (i) {
				scpi_rx_get_marker_level(i, true, &lvl);
				min_max = g_strsplit(value, " ", 0);
				if (lvl >= atof(min_max[1]) && lvl <= atof(min_max[0])) {
					printf("Marker%i (%f) didn't match requirements (%f - %f)\n",
						i, lvl, atof(min_max[0]), atof(min_max[1]));
					return "FAIL";
				}
			} else {
				return "FAIL";
			}
		}
	} else {
		printf("Unhandled tokens in ini file,\n"
				"\tSection %s\n\tAtttribute : %s\n\tValue: %s\n",
				"SCPI", attrib, value);
		if (value)
			return "FAIL";
	}

	return buf;
}
Exemple #30
0
/*****************************************************************************
                    snap by mode 1
 how to snap:
 1)only creat one snap group
 2)bind to a vichn to snap and then unbind
 3)repeat 2) to snap all vichn in turn

 features:
 1)save memory, because only one snap group and snap channel
 2)efficiency lower than mode 2, pictures snapped will not more than 8.
*****************************************************************************/
HI_VOID* thread_StartSnapByMode1(HI_VOID *p)
{
    HI_S32 s32Ret;
    VENC_GRP VeGroup = 0;
    VENC_CHN SnapChn = 0;
    VI_DEV ViDev = 0;
    VI_CHN ViChn = 0;
    FILE *pFile = NULL;
    HI_S32 s32SnapCnt = 0;
    HI_S32 s32SnapTotal;
    SNAP_MULTI_CHN_S *pstSnapMultiChn = NULL;
    HI_S32 s32ViChnTotal;

    pstSnapMultiChn = (SNAP_MULTI_CHN_S*)p;
    VeGroup = pstSnapMultiChn->SnapGroup;
    SnapChn = pstSnapMultiChn->SnapChn;
    ViDev = pstSnapMultiChn->ViDev;
    s32ViChnTotal = pstSnapMultiChn->s32ViChnCnt;
    s32SnapTotal = pstSnapMultiChn->s32SnapTotal;

    /* snap all vi channels in sequence.
      * step 1: bind vi
      * step 2: register snap channel to group.
      * step 3: start snap channel to receiver picture.
      * step 4: get one-picture stream and save as jpeg file.
      * step 5: undo step 3, step 2, step 1.
      * step 6: chose next vi to snap, then go to step 1
      */
    ViChn = 0;
    while (HI_TRUE == pstSnapMultiChn->bThreadStart)
    {
        s32Ret = HI_MPI_VENC_BindInput(VeGroup, ViDev, ViChn);
        if (s32Ret != HI_SUCCESS)
        {
            printf("HI_MPI_VENC_BindInput err 0x%x\n", s32Ret);
            return NULL;
        }

        s32Ret = HI_MPI_VENC_RegisterChn(VeGroup, SnapChn);
        if (s32Ret != HI_SUCCESS)
        {
            printf("HI_MPI_VENC_RegisterChn err 0x%x\n", s32Ret);
            return NULL;
        }

        s32Ret = HI_MPI_VENC_StartRecvPic(SnapChn);
        if (s32Ret != HI_SUCCESS)
        {
            printf("HI_MPI_VENC_StartRecvPic err 0x%x\n", s32Ret);
            return NULL;
        }

        {
            /*save jpeg picture*/
            char acFile[128]  = {0};
            //struct timeval timenow;
            //gettimeofday(&timenow, NULL);
            sprintf(acFile, "Vichn%d_num%d.jpg", ViChn, s32SnapCnt);
            pFile = fopen(acFile, "wb");
            if (pFile == NULL)
            {
                printf("open file err\n");
                return NULL;
            }

            s32Ret = SAMPLE_GetSnapPic(SnapChn, pFile);
            if (s32Ret != HI_SUCCESS)
            {
                printf("SAMPLE_GetSnapPic err 0x%x\n", s32Ret);
                fclose(pFile);
                return NULL;
            }

            fclose(pFile);
        }

        s32Ret = HI_MPI_VENC_StopRecvPic(SnapChn);
        if (s32Ret != HI_SUCCESS)
        {
            printf("HI_MPI_VENC_StopRecvPic err 0x%x\n", s32Ret);
            return NULL;
        }

        s32Ret = HI_MPI_VENC_UnRegisterChn(SnapChn);
        if (s32Ret != HI_SUCCESS)
        {
            printf("HI_MPI_VENC_UnRegisterChn err 0x%x\n", s32Ret);
            return NULL;
        }

        s32Ret = HI_MPI_VENC_UnbindInput(VeGroup);
        if (s32Ret != HI_SUCCESS)
        {
            printf("HI_MPI_VENC_UnbindInput err 0x%x\n", s32Ret);
            return NULL;
        }

        /* continue to snap next vi channel */
        ViChn++;
        if(ViChn >= s32ViChnTotal)
        {
            ViChn = 0;
            s32SnapCnt++;
        }
    }

    return NULL;
}