コード例 #1
1
ファイル: tst-mmap2-eofsync.c プロジェクト: bminor/glibc
static int
do_test (void)
{
  const size_t pagesize = getpagesize ();
  FILE *f;
  char buf[pagesize];
  int result = 0;
  int c;

  f = fopen (temp_file, "rm");
  if (f == NULL)
    {
      perror (temp_file);
      return 1;
    }

  if (fread (buf, pagesize, 1, f) != 1)
    {
      perror ("fread");
      return 1;
    }

  if (memcmp (buf, pages, pagesize))
    {
      puts ("data mismatch in page 1");
      result = 1;
    }

  printf ("feof = %d, ferror = %d immediately after fread\n",
	  feof (f), ferror (f));

  c = fgetc (f);
  if (c == EOF)
    printf ("fgetc -> EOF (feof = %d, ferror = %d)\n",
	    feof (f), ferror (f));
  else
    {
      printf ("fgetc returned %o (feof = %d, ferror = %d)\n",
	      c, feof (f), ferror (f));
      result = 1;
    }

  c = write (temp_fd, pages + pagesize, pagesize);
  if (c == (ssize_t) pagesize)
    printf ("wrote more to file\n");
  else
    {
      printf ("wrote %d != %zd (%m)\n", c, pagesize);
      result = 1;
    }

  if (fread (buf, pagesize, 1, f) != 1)
    {
      printf ("second fread fails: feof = %d, ferror = %d (%m)\n",
	      feof (f), ferror (f));
      clearerr (f);
      if (fread (buf, pagesize, 1, f) != 1)
	{
	  printf ("retry fread fails: feof = %d, ferror = %d (%m)\n",
		  feof (f), ferror (f));
	  result = 1;
	}
    }
  if (result == 0 && memcmp (buf, pages + pagesize, pagesize))
    {
      puts ("data mismatch in page 2");
      result = 1;
    }

  fseek (f, pagesize - 1, SEEK_SET);
  c = fgetc (f);
  if (c != 'a')
    {
      printf ("fgetc at end of page 1 read '%c' (%m)\n", c);
      result = 1;
    }

  if (ftruncate (temp_fd, pagesize) < 0)
    {
      printf ("ftruncate failed: %m\n");
      result = 1;
    }

  fflush (f);

  c = fgetc (f);
  if (c == EOF)
    printf ("after truncate fgetc -> EOF (feof = %d, ferror = %d)\n",
	    feof (f), ferror (f));
  else
    {
      printf ("after truncate fgetc returned '%c' (feof = %d, ferror = %d)\n",
	      c, feof (f), ferror (f));
      result = 1;
    }

  fclose (f);

  return result;
}
コード例 #2
0
//
// Checking for all accessible drives.  Storing them, and returning the number
// of disks found.  Drives are reported in order so that Iometer does not
// need to sort them.
//
int Manager::Report_Disks( Target_Spec* disk_spec )
{
	TargetDisk	d;
	int		count = 0;
	char usedDevs[USED_DEVS_MAX_SIZE + 1];
	usedDevs[0] = '\0';

	cout << "Reporting drive information..." << endl;
	
	// *********************************************************************************
	// DEVELOPER NOTES
	// ---------------
	//
	// For linux, I return three sets of data:
	// 1) The root directory for all mounted normal (non-exclude_filesys) filesystems.
	//    These are our "logical" disks. They are found by scanning /etc/mtab.
	// 2) The device names supplied from command line.
	// 3) The device names for all unmounted block devices. These are our "physical"
	//    disks. They are found by reading /proc/partitions, then skipping all devices
	//    that are in mtab.
	//
	// **********************************************************************************
	
	//
	// First find all virtual disks by inspecting the mount table. Then search for
	// physical disks that aren't mounted.
	//


	if ((mnttab = getenv("MNTTAB")) == NULL)
		mnttab = _PATH_MOUNTED;

	FILE *file;
	if ((file = fopen(mnttab, "r")) == NULL)
	{
		cout << "open (mount tab) file " << mnttab << " failed with error " << errno << endl;
		cout << "Set environment variable MNTTAB to correct pathname" << endl;
		exit(1);
	}
	
	struct mntent *ment;

	int length;
	char disk_name[MAX_NAME];

	while ((ment = getmntent(file)) != NULL)
	{
#ifdef _DEBUG
		cout << "*** File system found: " << ment->mnt_fsname << "\n";
#endif
		if (!strncmp(ment->mnt_fsname, "/dev/", 5)) {
			// This is a real disk. Add it to our list of disks not to use as
			// physical devices.
			if (strlen(usedDevs) + 2 + strlen(ment->mnt_fsname + 5) >=
					USED_DEVS_MAX_SIZE) {
				cerr << "Too many devices for our list! Aborting.\n";
				exit(1);
			}
			strcat(usedDevs, " ");
			strcat(usedDevs, ment->mnt_fsname + 5);
			strcat(usedDevs, " ");
		}

		// see if the current file sys is an excluded file system type for dynamo.
		if (strstr(exclude_filesys, ment->mnt_type) != NULL) {
#ifdef _DEBUG
			cout << "*** File system type \"" << ment->mnt_type << "\" excluded.\n";
#endif
			continue;
		}

		length = MAX_NAME - strlen(ment->mnt_type);

		// take away 4 bytes from length for the decorations (spaces, [, ])
		length -= 4;

		strncpy(disk_name, ment->mnt_dir, length);
		disk_name[length] = 0;

		if ( ! d.Init_Logical( disk_name ) ) {
#ifdef _DEBUG
			cout << "*** " << __FUNCTION__ << ": Init_Logical failed.\n";
#endif
			continue;
		}

		// Drive exists and ready for use.
		d.spec.type = LogicalDiskType;
		memcpy( &disk_spec[count], &d.spec, sizeof( Target_Spec ) );

		disk_spec[count].name[length] = 0;
		// and TargetDisk::Init_Logical().
		strcat(disk_spec[count].name, " [");
		strcat(disk_spec[count].name, ment->mnt_type);
		strcat(disk_spec[count].name, "]");

#ifdef _DEBUG
			cout << "   Found " << disk_spec[count].name << "." << endl << flush;
#endif
		count++;
		if (count >= MAX_TARGETS)
			break;
	}
	fclose(file);

	if (count >= MAX_TARGETS)
		return count;

	cout << "  Physical drives (raw devices)..." << endl;
	
	int i, valid_devcnt;
	for (i = 0; i < MAX_TARGETS; i++) {
		if (blkdevlist[i][0] == 0) {
			break;
		}
		if (d.Init_Physical(blkdevlist[i])) {
			d.spec.type = PhysicalDiskType;
			memcpy(&disk_spec[count], &d.spec, sizeof(Target_Spec));
			if (++count >= MAX_TARGETS)
				return count;
		}
	}
	valid_devcnt = i;
	
	// Now reporting physical drives (raw devices). Data from /proc/partitions.
	// Example output from /proc/partitions:
	//////////////////////////////////////////////////////////////////////
	// major minor  #blocks  name
	//
	//    8     0    8887080 sda
	//    8     1    8225248 sda1
	//    8     2     658665 sda2
	//   22     0 1073741823 hdc
	//////////////////////////////////////////////////////////////////////
	// Note: In the above example, "hdc" is a CD-ROM, and "sda1" and "sda2" are
	// two partitions on the disk represented by "sda".
		
	file = fopen("/proc/partitions", "r");
	if (file == NULL) {
		cerr << "Open \"/proc/partitions\" failed (errno " << errno <<"). "
			"Cannot locate physical disks.\n";
		exit(1);
	}
	//
	// Pull out the first line. It just describes the columns. The second line
	// is blank, but fscanf will skip that automatically.
	//
	int c;
	do {
		c = getc(file);
	} while ((c != '\n') && (c != EOF));

	char devName[MAX_NAME], paddedDevName[MAX_NAME+2];
#if MAX_NAME != 80
 #warning ===> WARNING: You have to keep the fscanf() and MAX_NAME in sync!
 // "fscanf(... %<nn>s)" has to be "MAX_NAME - 1"
#endif
	while ((count < MAX_TARGETS) &&
				 (fscanf(file, "%*d %*d %*d %79s", devName) == 1)) {
		sprintf(paddedDevName, " %s ", devName);
#ifdef _DEBUG
		cout << __FUNCTION__ << ": Found device " << devName << "\n";
#endif
		if (strstr(usedDevs, paddedDevName) == NULL) {
			int duplicate;
			// Nobody has mounted this device. Try to open it for reading; if we can,
			// then add it to our list of physical devices.
#ifdef _DEBUG
			cout << __FUNCTION__ << ": Device is not mounted.\n";
#endif
			duplicate = 0;
			for (i = 0; i < valid_devcnt; i++) {
				if ((devName[0] == '/' && !strcmp(devName, blkdevlist[i])) ||
					(devName[0] != '/' && !strcmp(devName, blkdevlist[i] + strlen("/dev/")))) {
#ifdef _DEBUG
					cout << "Find duplicate dev:" << devName << ", Ignoring." << endl;
#endif
					duplicate = 1;
					break;
				}
			}
			if ((!duplicate) && d.Init_Physical(devName)) {
				d.spec.type = PhysicalDiskType;
				memcpy(&disk_spec[count], &d.spec, sizeof(Target_Spec));
				++count;
			}
		}
#ifdef _DEBUG
		else {
			cout << __FUNCTION__ << ": Device is mounted. Ignoring.\n";
		}
#endif

		//
		// Now we cut to the end of the line to get ready to start the next line.
		//
		do {
			c = fgetc(file);
		} while ((c != '\n') && (c != EOF));
	}
	fclose(file);
	qsort(disk_spec, count, sizeof(Target_Spec), compareRawDiskNames);
	return(count);
}
コード例 #3
0
ファイル: LOADPRIM.C プロジェクト: AleksandraSimonova/SUM2016
/* Load object from '*.g3d' file function.
 * ARGUMENTS:
 *   - object structure pointer:
 *       vg4OBJ *Obj;
 *   - file name:
 *       CHAR *FileName;
 * RETURNS:
 *   (BOOL) TRUE is success, FALSE otherwise.
 */
BOOL VG4_RndObjLoad( vg4OBJ *Obj, CHAR *FileName )
{
  FILE *F;
  DWORD Sign;
  INT NumOfPrimitives;
  CHAR MtlFile[300];
  INT NumOfV;
  INT NumOfI;
  CHAR Mtl[300];
  INT p;
  vg4VERTEX *V;
  INT *I;

  memset(Obj, 0, sizeof(vg4OBJ));

  F = fopen(FileName, "rb");
  if (F == NULL)
    return FALSE;

  /* File structure:
   *   4b Signature: "G3D\0"    CHAR Sign[4];
   *   4b NumOfPrimitives       INT NumOfPrimitives;
   *   300b material file name: CHAR MtlFile[300];
   *   repeated NumOfPrimitives times:
   *     4b INT NumOfV; - vertex count
   *     4b INT NumOfI; - index (triangles * 3) count
   *     300b material name: CHAR Mtl[300];
   *     repeat NumOfV times - vertices:
   *         !!! float point -> FLT
   *       typedef struct
   *       {
   *         VEC  P;  - Vertex position
   *         VEC2 T;  - Vertex texture coordinates
   *         VEC  N;  - Normal at vertex
   *         VEC4 C;  - Vertex color
   *       } VERTEX;
   *     repeat (NumOfF / 3) times - facets (triangles):
   *       INT N0, N1, N2; - for every triangle (N* - vertex number)
   */
  fread(&Sign, 4, 1, F);
  if (Sign != *(DWORD *)"G3D")
  {
    fclose(F);
    return FALSE;
  }
  fread(&NumOfPrimitives, 4, 1, F);
  fread(MtlFile, 1, 300, F);
  VG4_RndLoadMaterials(MtlFile);

  /* Allocate mnemory for primitives */
  if ((Obj->Prims = malloc(sizeof(vg4PRIM) * NumOfPrimitives)) == NULL)
  {
    fclose(F);
    return FALSE;
  }
  Obj->NumOfPrims = NumOfPrimitives;

  for (p = 0; p < NumOfPrimitives; p++)
  {
    /* Read primitive info */
    fread(&NumOfV, 4, 1, F);
    fread(&NumOfI, 4, 1, F);
    fread(Mtl, 1, 300, F);

    /* Allocate memory for primitive */
    if ((V = malloc(sizeof(vg4VERTEX) * NumOfV + sizeof(INT) * NumOfI)) == NULL)
    {
      while (p-- > 0)
      {
        glBindVertexArray(Obj->Prims[p].VA);
        glBindBuffer(GL_ARRAY_BUFFER, 0);
        glDeleteBuffers(1, &Obj->Prims[p].VBuf);
        glBindVertexArray(0);
        glDeleteVertexArrays(1, &Obj->Prims[p].VA);
        glDeleteBuffers(1, &Obj->Prims[p].IBuf);
      }
      free(Obj->Prims);
      memset(Obj, 0, sizeof(vg4OBJ));
      fclose(F);
      return FALSE;
    }
    I = (INT *)(V + NumOfV);
    Obj->Prims[p].NumOfI = NumOfI;
    Obj->Prims[p].M = MatrIdentity();
    Obj->Prims[p].MtlNo = VG4_RndFindMaterial(Mtl);
    fread(V, sizeof(vg4VERTEX), NumOfV, F);
    fread(I, sizeof(INT), NumOfI, F);

    /* Create OpenGL buffers */
    glGenVertexArrays(1, &Obj->Prims[p].VA);
    glGenBuffers(1, &Obj->Prims[p].VBuf);
    glGenBuffers(1, &Obj->Prims[p].IBuf);

    /* Activate vertex array */
    glBindVertexArray(Obj->Prims[p].VA);
    /* Activate vertex buffer */
    glBindBuffer(GL_ARRAY_BUFFER, Obj->Prims[p].VBuf);
    /* Store vertex data */
    glBufferData(GL_ARRAY_BUFFER, sizeof(vg4VERTEX) * NumOfV, V, GL_STATIC_DRAW);

    /* Setup data order */
    /*                    layout,
     *                      components count,
     *                          type
     *                                    should be normalize,
     *                                           vertex structure size in bytes (stride),
     *                                               offset in bytes to field start */
    glVertexAttribPointer(0, 3, GL_FLOAT, FALSE, sizeof(vg4VERTEX),
                          (VOID *)0); /* position */
    glVertexAttribPointer(1, 2, GL_FLOAT, FALSE, sizeof(vg4VERTEX),
                          (VOID *)sizeof(VEC)); /* texture coordinates */
    glVertexAttribPointer(2, 3, GL_FLOAT, FALSE, sizeof(vg4VERTEX),
                          (VOID *)(sizeof(VEC) + sizeof(VEC2))); /* normal */
    glVertexAttribPointer(3, 4, GL_FLOAT, FALSE, sizeof(vg4VERTEX),
                          (VOID *)(sizeof(VEC) * 2 + sizeof(VEC2))); /* color */

    /* Enable used attributes */
    glEnableVertexAttribArray(0);
    glEnableVertexAttribArray(1);
    glEnableVertexAttribArray(2);
    glEnableVertexAttribArray(3);

    /* Indices */
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, Obj->Prims[p].IBuf);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(INT) * NumOfI, I, GL_STATIC_DRAW);

    /* Disable vertex array */
    glBindVertexArray(0);

    free(V);
  }
  fclose(F);
  return TRUE;
} /* End of 'VG4_RndObjLoad' function */
コード例 #4
0
ファイル: dvtmcf1_r.c プロジェクト: zaharchuktv/linuxbuh
gint dvtmcf1_r1(class dvtmcf1_r_data *data)
{
    time_t vremn;
    time(&vremn);
    char strsql[1024];
    iceb_u_str repl;
    iceb_clock sss(data->window);





    short ostkg=0;

    iceb_poldan("Отчет в килограммах",strsql,"matnast.alx",data->window);
    if(iceb_u_SRAV(strsql,"Вкл",1) == 0)
        ostkg=1;

    sprintf(strsql,"select * from Kart");
    SQLCURSOR cur,curtmp;
    SQLCURSOR cur1;
    SQL_str row,rowtmp;
    SQL_str row1;

    int kolstr;

    if((kolstr=cur.make_cursor(&bd,strsql)) < 0)
        iceb_msql_error(&bd,gettext("Ошибка создания курсора !"),strsql,data->window);

    if(kolstr == 0)
    {
        iceb_menu_soob(gettext("Не найдено ни одной записи !"),data->window);
        sss.clear_data();
        gtk_widget_destroy(data->window);
        return(FALSE);
    }

    class iceb_tmptab tabtmp;
    const char *imatmptab= {"dvtmcf1"};

    char zaprostmp[512];
    memset(zaprostmp,'\0',sizeof(zaprostmp));

    sprintf(zaprostmp,"CREATE TEMPORARY TABLE %s (\
sh char(24) not null,\
skl int not null,\
kgm int not null,\
naim char(112) not null,\
km int not null,\
nk int not null,\
ei char(24) not null,\
cena double(15,6) not null,\
nds float(2) not null,\
mnds smallint not null,\
fas float(2) not null)",imatmptab);


    if(tabtmp.create_tab(imatmptab,zaprostmp,data->window) != 0)
    {
        sss.clear_data();
        gtk_widget_destroy(data->window);
        return(FALSE);
    }
    /*********
    char imaftmp[32];
    FILE *ff1;

    sprintf(imaftmp,"dv%d.tmp",getpid());
    if((ff1 = fopen(imaftmp,"w")) == NULL)
     {
      iceb_er_op_fil(imaftmp,"",errno,data->window);
      sss.clear_data();
      gtk_widget_destroy(data->window);
      return(FALSE);
     }
    **************/
    short dn,mn,gn;
    short dk,mk,gk;

    iceb_rsdatp(&dn,&mn,&gn,data->rk->datan.ravno(),&dk,&mk,&gk,data->rk->datak.ravno(),data->window);

    sprintf(strsql,"%s\n%s %d.%d.%d %s %d.%d.%d\n",
            gettext("Сортируем записи"),
            gettext("Период с"),
            dn,mn,gn,
            gettext("по"),
            dk,mk,gk);

    iceb_printw(iceb_u_toutf(strsql),data->buffer,data->view);

    int kgrm=0;
//int kolstr2=0;
    float kolstr1=0.;
    class iceb_u_str naim("");

    while(cur.read_cursor(&row) != 0)
    {
        iceb_pbar(data->bar,kolstr,++kolstr1);

        if(iceb_u_proverka(data->rk->sklad.ravno(),row[0],0,0) != 0)
            continue;

        if(iceb_u_proverka(data->rk->shet.ravno(),row[5],0,0) != 0)
            continue;

        kgrm=0;
        naim.new_plus("");
        /*Читаем код группы материалла*/
        sprintf(strsql,"select kodgr,naimat from Material where kodm=%s",row[2]);
        if(sql_readkey(&bd,strsql,&row1,&cur1) != 1)
        {
            printf("%s %s !\n",gettext("Не найден код материалла"),row[2]);
            continue;
        }
        else
        {
            kgrm=atoi(row1[0]);
            naim.new_plus(row1[1]);
        }

        if(iceb_u_proverka(data->rk->grupa.ravno(),row1[0],0,0) != 0)
            continue;

        if(provndsw(data->rk->nds.ravno(),row) != 0)
            continue;

        if(iceb_u_proverka(data->rk->kodmat.ravno(),row[2],0,0) != 0)
            continue;

//  kolstr2++;
        /************
          fprintf(ff1,"%s|%s|%d|%s|%s|%s|%s|%.10g|%.5g|%s|%s|\n",
          row[5],row[0],kgrm,naim.ravno(),row[2],row[1],row[4],atof(row[6]),atof(row[9]),
          row[3],row[10]);
        *************/
        sprintf(strsql,"insert into %s values ('%s',%s,%d,'%s',%s,%s,'%s',%.10g,%.5g,%s,%s)",
                imatmptab,
                row[5],row[0],kgrm,naim.ravno_filtr(),row[2],row[1],row[4],atof(row[6]),atof(row[9]),
                row[3],row[10]);
        iceb_sql_zapis(strsql,1,0,data->window);

    }

//fclose(ff1);


    if(data->rk->metka_sort == 0) //Сортировать счет-склад-наименование материалла.
    {
//  sprintf(strsql,"sort -o %s -t\\| -k1,2 -k2,3n -k4,5 %s",imaftmp,imaftmp);
//  sprintf(strsql,"sort -o %s -t\\| +0 -1 +1n -2 +3 -4 %s",imaftmp,imaftmp);
        sprintf(strsql,"select * from %s order by sh asc,skl asc,naim asc",imatmptab);
    }
    if(data->rk->metka_sort == 1) //Сортировать счет-склад-группа-наименование материалла.
    {
//  sprintf(strsql,"sort -o %s -t\\| -k1,2 -k2,3n -k3,4n -k4,5 %s",imaftmp,imaftmp);
//  sprintf(strsql,"sort -o %s -t\\| +0 -1 +1n -2 +2n -3 +3 -4 %s",imaftmp,imaftmp);
        sprintf(strsql,"select * from %s order by sh asc,skl asc,kgm asc,naim asc",imatmptab);
    }
//system(strsql); //Запуск сортировки
    int kolstrtmp=0;
    if((kolstrtmp=curtmp.make_cursor(&bd,strsql)) < 0)
    {
        iceb_msql_error(&bd,gettext("Ошибка создания курсора !"),strsql,data->window);
        sss.clear_data();
        gtk_widget_destroy(data->window);
        return(FALSE);
    }

    sprintf(strsql,"%s.\n",gettext("Делаем отчет"));
    iceb_printw(iceb_u_toutf(strsql),data->buffer,data->view);
    /**************
    if((ff1 = fopen(imaftmp,"r")) == NULL)
     {
      iceb_er_op_fil(imaftmp,"",errno,data->window);
      gtk_widget_destroy(data->window);
      return(FALSE);
     }
    *************/
    FILE *ff;
    char imaf[32];

    sprintf(imaf,"zag%d.lst",getpid());
    data->rk->imaf.plus(imaf);

    repl.new_plus(gettext("Оборотная ведомость движния товарно-материальных ценностей"));
    repl.plus(" (");
    repl.plus(gettext("формат"));
    repl.plus(" A3)");

    data->rk->naimf.plus(repl.ravno());

    if((ff = fopen(imaf,"w")) == NULL)
    {
        iceb_er_op_fil(imaf,"",errno,data->window);
        sss.clear_data();
        gtk_widget_destroy(data->window);
        return(FALSE);
    }
    FILE *ffuz;
    char imafuz[32];

    sprintf(imafuz,"zaguz%d.lst",getpid());
    data->rk->imaf.plus(imafuz);

    repl.new_plus(gettext("Оборотная ведомость движния товарно-материальных ценностей"));
    repl.plus(" (");
    repl.plus(gettext("формат"));
    repl.plus(" A4)");

    data->rk->naimf.plus(repl.ravno());

    if((ffuz = fopen(imafuz,"w")) == NULL)
    {
        iceb_er_op_fil(imafuz,"",errno,data->window);
        sss.clear_data();
        gtk_widget_destroy(data->window);
        return(FALSE);
    }

    /***************
    if(tipras == 1)
     {
      sprintf(imafkl2,"zagg%d.lst",getpid());

      if((ffkl2 = fopen(imafkl2,"w")) == NULL)
       ERROR1(gettext("Ошибка открытия файла"),errno,imafkl2);
      startfil(ffkl2);
     }
    else
     {
    *****************/
    char imafitog[32];
    sprintf(imafitog,"zai%d.lst",getpid());
    data->rk->imaf.plus(imafitog);

    data->rk->naimf.plus(gettext("Свод движения материальных ценностей"));
    FILE *ffitog;
    if((ffitog = fopen(imafitog,"w")) == NULL)
    {
        iceb_er_op_fil(imafitog,"",errno,data->window);
        sss.clear_data();
        gtk_widget_destroy(data->window);
        return(FALSE);
    }


    iceb_u_zagolov(gettext("Свод движения материальных ценностей"),dn,mn,gn,dk,mk,gk,organ,ffitog);


    iceb_u_zagolov(gettext("Оборотная ведомость движния товарно-материальных ценностей"),dn,mn,gn,dk,mk,gk,organ,ff);
    iceb_u_zagolov(gettext("Оборотная ведомость движния товарно-материальных ценностей"),dn,mn,gn,dk,mk,gk,organ,ffuz);


    int kst=4;

    if(data->rk->shet.getdlinna() > 1)
    {
        fprintf(ff,"%s:%s\n",gettext("Счёт"),data->rk->shet.ravno());
        fprintf(ffuz,"%s:%s\n",gettext("Счёт"),data->rk->shet.ravno());
        kst++;
    }
    if(data->rk->sklad.getdlinna() > 1)
    {
        fprintf(ff,"%s:%s\n",gettext("Склад"),data->rk->sklad.ravno());
        fprintf(ffuz,"%s:%s\n",gettext("Склад"),data->rk->sklad.ravno());
        kst++;
    }
    if(data->rk->grupa.getdlinna() > 1)
    {
        fprintf(ff,"%s:%s\n",gettext("Група"),data->rk->grupa.ravno());
        fprintf(ffuz,"%s:%s\n",gettext("Група"),data->rk->grupa.ravno());
        kst++;
    }

    if(data->rk->kodmat.getdlinna() > 1)
    {
        fprintf(ff,"%s:%s\n",gettext("Код материалла"),data->rk->kodmat.ravno());
        fprintf(ffuz,"%s:%s\n",gettext("Код материалла"),data->rk->kodmat.ravno());
        kst++;
    }
    if(data->rk->nds.getdlinna() > 1)
    {
        fprintf(ff,"%s:%s\n",gettext("НДС"),data->rk->nds.ravno());
        fprintf(ffuz,"%s:%s\n",gettext("НДС"),data->rk->nds.ravno());
        kst++;
    }
    char shbm[32];
    char naiskl[112];

    memset(shbm,'\0',sizeof(shbm));
    memset(naiskl,'\0',sizeof(naiskl));
    int skl=0;
    int sli=1;
    double itg1=0.,itg2=0.,itg3=0.,itg4=0.,itg5=0.,itg6=0.,itg7=0.,itg8=0.;
    double k1=0.,s1=0.,k2=0.,s2=0.,k3=0.,s3=0.,k4=0.,s4=0.;
    double kk1=0.,ss1=0.,kk2=0.,ss2=0.,kk3=0.,ss3=0.,kk4=0.,ss4=0.;
    double kg0=0.,kg1=0.,kg2=0.,kg3=0.;
    double kgs0=0.,kgs1=0.,kgs2=0.,kgs3=0.;
    int kgrmzp=0;
    char str[512];
    memset(str,'\0',sizeof(str));
    memset(str,'.',233);
    int mvsh=0;
    kolstr1=0;
//char str1[1000];
    class ostatok ost;
    char shb[20];
    int skl1;
    int kodm;
    int nk;
    char ei[32];
    char		mnds='\0';
    double cena,nds;
    char naimshet[512];
    char nomn[112];

//while(fgets(str1,sizeof(str1),ff1) != NULL)
// {
    while(curtmp.read_cursor(&rowtmp) != 0)
    {
        iceb_pbar(data->bar,kolstrtmp,++kolstr1);

        /********
          iceb_u_pole(str1,shb,1,'|');
          iceb_u_pole(str1,strsql,2,'|');
          skl1=atoi(strsql);
          iceb_u_pole(str1,strsql,3,'|');
          kgrm=atoi(strsql);

          iceb_u_pole(str1,naim,4,'|');
          iceb_u_pole(str1,strsql,5,'|');
          kodm=atoi(strsql);
          iceb_u_pole(str1,strsql,6,'|');
          nk=atoi(strsql);
        **************/
        strncpy(shb,rowtmp[0],sizeof(shb)-1);
        skl1=atoi(rowtmp[1]);
        kgrm=atoi(rowtmp[2]);
        naim.new_plus(rowtmp[3]);
        kodm=atoi(rowtmp[4]);
        nk=atoi(rowtmp[5]);

        /*Остаток по карточкам*/
        ostkarw(dn,mn,gn,dk,mk,gk,skl1,nk,&ost);

        if(ost.ostm[0] == 0. && ost.ostm[1] == 0. && ost.ostm[3] == 0. && fabs(ost.ostmc[3]) < 0.009)
            continue;
        /************
          iceb_u_pole(str1,ei,7,'|');
          iceb_u_pole(str1,strsql,8,'|');
          cena=atof(strsql);
          iceb_u_pole(str1,strsql,9,'|');
          nds=atof(strsql);

          iceb_u_pole(str1,strsql,10,'|');
        ***********/
        strncpy(ei,rowtmp[6],sizeof(ei)-1);
        cena=atof(rowtmp[7]);
        nds=atof(rowtmp[8]);
        strncpy(strsql,rowtmp[9],sizeof(strsql)-1);

        if(atoi(strsql) == 0)
            mnds=' ';
        if(atoi(strsql) == 1)
            mnds='+';

        if(kgrmzp != kgrm)
        {
            if(kgrmzp != 0)
            {
                if(data->rk->metka_sort == 1)
                    if(itg1 != 0. || itg2 != 0. || itg3 != 0. || itg4 != 0.)
                    {
                        itgrup(kgrmzp,itg1,itg2,itg3,itg4,itg5,itg6,itg7,itg8,ffuz,0,ff);
                        kst+=2;
                    }
            }
            itg1=itg2=itg3=itg4=itg5=itg6=itg7=itg8=0.;
            kgrmzp=kgrm;
        }

        if(iceb_u_SRAV(shb,shbm,1) != 0)
        {
            if(shbm[0] != '\0')
            {
                if(data->rk->metka_sort == 1)
                    if(itg1 != 0. || itg2 != 0. || itg3 != 0. || itg4 != 0.)
                    {
                        itgrup(kgrmzp,itg1,itg2,itg3,itg4,itg5,itg6,itg7,itg8,ffuz,0,ff);
                        itg1=itg2=itg3=itg4=itg5=itg6=itg7=itg8=0.;
                        kst+=2;
                    }
                itskl(skl,kk1,kk2,kk3,kk4,ss1,ss2,ss3,ss4,ffuz,ff,ffitog,data);
                kst+=2;
                if(ostkg == 1 && fabs((kk1+kk2+kk3+kk4) - (kg0+kg1+kg2+kg3)) > 0.0001 &&
                        kg0+kg1+kg2+kg3 > 0.0001)
                {
                    itkg(shbm,skl,kg0,kg1,kg2,kg3,1,ffuz,ff);
                    kst+=2;
                    kg0=kg1=kg2=kg3=0.;
                }
                itsh(shbm,k1,k2,k3,k4,s1,s2,s3,s4,ffuz,ff,ffitog,data);
                kst+=2;
                if(ostkg == 1 && fabs((k1+k2+k3+k4) - (kgs0+kgs1+kgs2+kgs3)) > 0.0001 &&
                        kgs0+kgs1+kgs2+kgs3 > 0.0001)
                {
                    itkg(shbm,skl,kgs0,kgs1,kgs2,kgs3,0,ffuz,ff);
                    kst+=2;
                    kgs0=kgs1=kgs2=kgs3=0.;
                }
                skl=0;
                /****************
                      if(tipras == 1)
                       {
                	itskl1(skl,kk1,kk2,kk3,kk4,ss1,ss2,ss3,ss4,str,ff,ffkl2);
                	skl=0;
                	itsh1(shbm,k1,k2,k3,k4,s1,s2,s3,s4,str,ff,ffkl2);
                	kst+=4;
                       }
                *******************/
            }
            k1=s1=k2=s2=k3=s3=k4=s4=0.;

            /*Читаем наименование счета*/
            memset(naimshet,'\0',sizeof(naimshet));
            sprintf(strsql,"select nais from Plansh where ns='%s'",shb);
            if(sql_readkey(&bd,strsql,&row,&cur1) != 1)
            {
                printf("Не найден счет %s в плане счетов !\n",shb);
                fprintf(ff,"%s %s !\n",gettext("Не найден счет"),shb);
            }
            else
                strncpy(naimshet,row[0],sizeof(naimshet)-1);

            sprintf(strsql,"\n%s %s \"%s\"\n",gettext("Счет"),shb,naimshet);
            iceb_printw(iceb_u_toutf(strsql),data->buffer,data->view);

            if(kst > kol_strok_na_liste - 10)
            {
                fprintf(ff,"\f");
                fprintf(ffuz,"\f");
//      if(ffkl2 != NULL)
//         fprintf(ffkl2,"\f");
                kst=0;
                sli++;
            }


            fprintf(ff,"\n%s %s \"%s\"\n",gettext("Счет"),shb,naimshet);
            fprintf(ffuz,"\n%s %s \"%s\"\n",gettext("Счет"),shb,naimshet);
            if(ffitog != NULL)
                fprintf(ffitog,"\n%s %s \"%s\"\n",gettext("Счет"),shb,naimshet);
            kst+=2;
//    if(tipras == 0)
            gsapp(dn,mn,gn,dk,mk,gk,&sli,&kst,skl1,naiskl,ffuz,ff);
//    else
//     gsapp2(dn,mn,gn,dk,mk,gk,&sli,&kst,skl1,naiskl,str,ff,ffkl2);

            mvsh=1;

            strcpy(shbm,shb);
        }

        if(skl != skl1)
        {
            if(skl != 0)
            {
                if(data->rk->metka_sort == 1)
                    if(itg1 != 0. || itg2 != 0. || itg3 != 0. || itg4 != 0.)
                    {
                        itgrup(kgrmzp,itg1,itg2,itg3,itg4,itg5,itg6,itg7,itg8,ffuz,0,ff);
                        itg1=itg2=itg3=itg4=itg5=itg6=itg7=itg8=0.;
                        kst+=2;
                    }

                itskl(skl,kk1,kk2,kk3,kk4,ss1,ss2,ss3,ss4,ffuz,ff,ffitog,data);
                kst+=2;
                if(ostkg == 1 && fabs((kk1+kk2+kk3+kk4) - (kg0+kg1+kg2+kg3)) > 0.0001 &&
                        kg0+kg1+kg2+kg3 > 0.0001)
                {
                    itkg(shbm,skl,kg0,kg1,kg2,kg3,1,ffuz,ff);
                    kst+=2;
                    kg0=kg1=kg2=kg3=0.;
                }

//      if(tipras == 1)
//       {
//	itskl1(skl,kk1,kk2,kk3,kk4,ss1,ss2,ss3,ss4,str,ff,ffkl2);
//        kst+=2;
//       }
            }
            kk1=ss1=kk2=ss2=kk3=ss3=kk4=ss4=0.;

            /*Читаем наименование склада*/
            memset(naiskl,'\0',sizeof(naiskl));
            sprintf(strsql,"select naik from Sklad where kod='%d'",skl1);
            if(sql_readkey(&bd,strsql,&row,&cur1) != 1)
            {
                printf("Не найден склад %d в списке складов\n",skl1);
                fprintf(ff,"%s %d !\n",gettext("Не найден склад"),skl1);
            }
            strncpy(naiskl,row[0],sizeof(naiskl));

            sprintf(strsql,"%s: %d %s\n",gettext("Склад"),skl1,naiskl);
            iceb_printw(iceb_u_toutf(strsql),data->buffer,data->view);

            if(kst != 0)
                if(kst > kol_strok_na_liste - 10)
                {
                    fprintf(ff,"\f");
                    fprintf(ffuz,"\f");
//      if(ffkl2 != NULL)
//         fprintf(ffkl2,"\f");
                    kst=0;
                    sli++;
                }
            mvsh=1;
            skl=skl1;

        }
        if(mvsh == 1)
        {
//    if(tipras == 0)
//     {
            shdtmcf1(dn,mn,gn,dk,mk,gk,sli,ff,skl,naiskl,ffuz);
            kst+=6;
//     }
            /***************
                if(tipras == 1)
                 {
                  shdtmcf1k(dn,mn,gn,sli,ff,skl,naiskl,ffkl2);
                  kst+=6;
                 }
            ***************/
            mvsh=0;
        }


        /*Остаток по карточкам*/
//  ostkar(dn,mn,gn,dk,mk,gk,skl1,nk,ostg,ostm,ostgc,ostmc);

//  sprintf(nomn,"%d.%s.%d.%d",skl1,shb,kgrm,nk);
        sprintf(nomn,"%s.%d.%d",shb,kgrm,nk);


//  if(tipras == 0)
//   {
        gsapp(dn,mn,gn,dk,mk,gk,&sli,&kst,skl1,naiskl,ffuz,ff);

        fprintf(ff,"\
%4d %-*.*s %-*s %-*s %c%2.2g %14.10g %15.10g %15.2f %15.10g %15.2f %15.10g %15.2f \
%15.10g %15.2f\n",
                kodm,
                iceb_u_kolbait(40,naim.ravno()),iceb_u_kolbait(40,naim.ravno()),naim.ravno(),
                iceb_u_kolbait(13,nomn),nomn,
                iceb_u_kolbait(10,ei),ei,
                mnds,nds,cena,
                ost.ostm[0],ost.ostmc[0],ost.ostm[1],ost.ostmc[1],ost.ostm[2],ost.ostmc[2],ost.ostm[3],ost.ostmc[3]);

        fprintf(ffuz,"\
%4d %-*.*s %-*s %-*s %c%2.2g %7s %8.8g %8.2f %8.8g %8.2f %8.8g %8.2f \
%8.8g %8.2f\n",
                kodm,
                iceb_u_kolbait(23,naim.ravno()),iceb_u_kolbait(23,naim.ravno()),naim.ravno(),
                iceb_u_kolbait(13,nomn),nomn,
                iceb_u_kolbait(3,ei),ei,
                mnds,nds,iceb_prcn(cena),
                ost.ostm[0],ost.ostmc[0],ost.ostm[1],ost.ostmc[1],ost.ostm[2],ost.ostmc[2],ost.ostm[3],ost.ostmc[3]);


        if(ostkg == 1)
        {
            double ost1=0.,ost2=0.,ost3=0.,ost4=0.;
            double fas=0.;
//       iceb_u_pole(str1,strsql,11,'|');
//       fas=atof(strsql);
            fas=atof(rowtmp[10]);
            if(fas > 0.0000001)
            {
                ost1=ost.ostm[0]*fas;
                ost2=ost.ostm[1]*fas;
                ost3=ost.ostm[2]*fas;
                ost4=ost.ostm[3]*fas;
                kg0+=ost1;
                kg1+=ost2;
                kg2+=ost3;
                kg3+=ost4;
                kgs0+=ost1;
                kgs1+=ost2;
                kgs2+=ost3;
                kgs3+=ost4;

                gsapp(dn,mn,gn,dk,mk,gk,&sli,&kst,skl1,naiskl,ffuz,ff);

                fprintf(ff,"\
%4s %-40.40s %-13s %-10s %3s %14s %15.10g %15s %15.10g %15s %15.10g %15s \
%15.10g %15s\n"," "," "," "," "," "," ",
                        ost1," ",ost2," ",ost3," ",ost4," ");

                fprintf(ffuz,"\
%4s %-23.23s %-13s %-3s %3s %7s %8.8g %8s %8.8g %8s %8.8g %8s \
%8.8g %8s\n"," "," "," "," "," "," ",
                        ost1," ",ost2," ",ost3," ",ost4," ");

            }
            else if(iceb_u_SRAV(ei,"Кг",0) == 0 || iceb_u_SRAV(ei,"кг",0) == 0 ||
コード例 #5
0
static void
MakeCache(const std::string &prefix, int argc, char *argv[], bool _doEmbedded)
{
	MPI_Status status;
	int xi;
 	std::map<std::string, std::list<std::string> >::const_iterator pIter;
	int np, me; 

	cachePath = prefix;

	MPI_Init(&argc, &argv);
	MPI_Comm_size(MPI_COMM_WORLD, &np);
	MPI_Comm_rank(MPI_COMM_WORLD, &me);

	doEmbedded = _doEmbedded;

	LoadEverything();
//	outputFormat = CLONEWISE_OUTPUT_XML;
	printf("# loaded everything\n");
	fflush(stdout);

	if (embeddedOnly) {
		std::map<std::string, std::set<std::string> >::const_iterator eIter;

		if (embeddedList.size() == 0) {
			char s[1024];

		        snprintf(s, sizeof(s), "/var/lib/Clonewise/clones/distros/%s/embedded-code-copies", distroString);
		        LoadEmbeddedCodeCopiesList(s);
		}
		for (	eIter  = embeddedList.begin(), xi = 0;
			eIter != embeddedList.end();
			eIter++)
		{
			vPackages.push_back(eIter->first);
			packageQueue.push_back(xi++);
		}
	} else {
		for (	pIter  = packages.begin(), xi = 0;
			pIter != packages.end();
			pIter++)
		{
			vPackages.push_back(pIter->first);
			packageQueue.push_back(xi++);
		}
	}

	printf("# going to scan %i packages\n", xi);
	fflush(stdout);
	if (me == 0) {
		while (packageQueue.size() != 0) {
			int index, which;

			MPI_Recv(&which, 1, MPI_INT, MPI_ANY_SOURCE, TAG1, MPI_COMM_WORLD, &status); 
			index = packageQueue.front();
			packageQueue.pop_front();
			MPI_Send(&index, 1, MPI_INT, which, TAG1, MPI_COMM_WORLD); 
		}
		for (int i = 1; i < np; i++) {
			int which, neg = -1;

			MPI_Recv(&which, 1, MPI_INT, i, TAG1, MPI_COMM_WORLD, &status); 
			MPI_Send(&neg, 1, MPI_INT, i, TAG1, MPI_COMM_WORLD); 
		}
		for (size_t i = 0; i < vPackages.size(); i++) { 
			int which;
			int r[2], size;
			char *result;
			FILE *f;
			char s[1024];

			MPI_Recv(&which, 1, MPI_INT, MPI_ANY_SOURCE, TAG1, MPI_COMM_WORLD, &status); 
			MPI_Recv(r, 2, MPI_INT, which, TAG1, MPI_COMM_WORLD, &status); 

			size = r[1];
			result = new char[size];

			MPI_Recv(result, size, MPI_CHAR, which, TAG1, MPI_COMM_WORLD, &status); 

			snprintf(s, sizeof(s), "/var/lib/Clonewise/clones/distros/%s/%s/%s", distroString, prefix.c_str(), vPackages[r[0]].c_str());
			f = fopen(s, "w");
			fwrite(result, 1, size, f);
			fclose(f), f = NULL;

			delete [] result;
		}
	} else {
		DoWorkLoop(me);
	}

	MPI_Finalize(); 
	exit(0); 
}
コード例 #6
0
int main(int argc, char **argv)
{
#ifdef MEMLEAK_CHECK
	atexit(DumpUnfreed);
#endif

#ifdef OBJECT_DEBUG
	atexit(object_dump);
#endif

	gst_init(&argc, &argv);

	// set pythonpath if unset
	setenv("PYTHONPATH", eEnv::resolve("${libdir}/enigma2/python").c_str(), 0);
	printf("PYTHONPATH: %s\n", getenv("PYTHONPATH"));
	printf("DVB_API_VERSION %d DVB_API_VERSION_MINOR %d\n", DVB_API_VERSION, DVB_API_VERSION_MINOR);

	bsodLogInit();

	ePython python;
	eMain main;

#if 1
	ePtr<gMainDC> my_dc;
	gMainDC::getInstance(my_dc);

	//int double_buffer = my_dc->haveDoubleBuffering();

	ePtr<gLCDDC> my_lcd_dc;
	gLCDDC::getInstance(my_lcd_dc);


		/* ok, this is currently hardcoded for arabic. */
			/* some characters are wrong in the regular font, force them to use the replacement font */
	for (int i = 0x60c; i <= 0x66d; ++i)
		eTextPara::forceReplacementGlyph(i);
	eTextPara::forceReplacementGlyph(0xfdf2);
	for (int i = 0xfe80; i < 0xff00; ++i)
		eTextPara::forceReplacementGlyph(i);

	eWidgetDesktop dsk(my_dc->size());
	eWidgetDesktop dsk_lcd(my_lcd_dc->size());

	dsk.setStyleID(0);
	dsk_lcd.setStyleID(my_lcd_dc->size().width() == 96 ? 2 : 1);

/*	if (double_buffer)
	{
		eDebug("[MAIN] - double buffering found, enable buffered graphics mode.");
		dsk.setCompositionMode(eWidgetDesktop::cmBuffered);
	} */

	wdsk = &dsk;
	lcddsk = &dsk_lcd;

	dsk.setDC(my_dc);
	dsk_lcd.setDC(my_lcd_dc);

	dsk.setBackgroundColor(gRGB(0,0,0,0xFF));
#endif

		/* redrawing is done in an idle-timer, so we have to set the context */
	dsk.setRedrawTask(main);
	dsk_lcd.setRedrawTask(main);

	eDebug("Checking box...");
	
	FILE *infile;
	char line[100];
	char command[64];

	if((infile = fopen("/proc/stb/info/boxtype", "r")) != NULL)
	{
		fgets(line, sizeof(line), infile);
	    
		if(strcmp(line, "ini-5000sv\n") == 0) 
		{
			eDebug("Miraclebox Premium Twin detected");
		}
		else if(strcmp(line, "ini-1000sv\n") == 0) 
		{
			eDebug("Miraclebox PremiumMini detected");
		}
		else if(strcmp(line, "ini-2000sv\n") == 0) 
		{
			eDebug("Miraclebox Premium Mini Plus detected");
		}		
		else if(strcmp(line, "ini-8000sv\n") == 0) 
		{
			eDebug("Miraclebox Premium Ultra detected");
		}
		else if(strcmp(line, "g300\n") == 0) 
		{
			eDebug("Miraclebox Premium XXXXX detected");
		}
		else if(strcmp(line, "7000S\n") == 0) 
		{
			eDebug("Miraclebox Premium Micro detected");
		}
		else
		{
			eDebug("Wrong HW, this image can be only run on Miraclbox Premium Series");
			sprintf(command, "showiframe /usr/share/enigma2/box.mvi > /dev/null");
			system(command);
			sprintf(command, "flash_erase /dev/mtd/2 0 0");
			system(command);
			sprintf(command, "flash_erase /dev/mtd/4 0 0");
			system(command);
			sprintf(command, "flash_erase /dev/mtd/3 0 0");
			system(command);
			sprintf(command, "sleep 5;reboot -f");
		}
		fclose(infile);
	}
	
	eDebug("[MAIN] Loading spinners...");

	{
		int i;
#define MAX_SPINNER 64
		ePtr<gPixmap> wait[MAX_SPINNER];
		for (i=0; i<MAX_SPINNER; ++i)
		{
			char filename[64];
			std::string rfilename;
			snprintf(filename, sizeof(filename), "${datadir}/enigma2/skin_default/spinner/wait%d.png", i + 1);
			rfilename = eEnv::resolve(filename);
			loadPNG(wait[i], rfilename.c_str());

			if (!wait[i])
			{
				if (!i)
					eDebug("[MAIN] failed to load %s: %m", rfilename.c_str());
				else
					eDebug("[MAIN] found %d spinner!\n", i);
				break;
			}
		}
		if (i)
			my_dc->setSpinner(eRect(ePoint(100, 100), wait[0]->size()), wait, i);
		else
			my_dc->setSpinner(eRect(100, 100, 0, 0), wait, 1);
	}

	gRC::getInstance()->setSpinnerDC(my_dc);

	eRCInput::getInstance()->keyEvent.connect(slot(keyEvent));

	printf("[MAIN] executing main\n");

	bsodCatchSignals();
	catchTermSignal();

	setIoPrio(IOPRIO_CLASS_BE, 3);

	/* start at full size */
	eVideoWidget::setFullsize(true);

//	python.execute("mytest", "__main__");
	python.execFile(eEnv::resolve("${libdir}/enigma2/python/mytest.py").c_str());

	/* restore both decoders to full size */
	eVideoWidget::setFullsize(true);

	if (exit_code == 5) /* python crash */
	{
		eDebug("[MAIN] (exit code 5)");
		bsodFatal(0);
	}

	dsk.paint();
	dsk_lcd.paint();

	{
		gPainter p(my_lcd_dc);
		p.resetClip(eRect(ePoint(0, 0), my_lcd_dc->size()));
		p.clear();
		p.flush();
	}

	return exit_code;
}
コード例 #7
0
ファイル: ppmload.cpp プロジェクト: Yutassie/CG
void loadppmimage(char *imagename,struct ppmimg* simg){
	FILE *fp;
	char buff[255];
	int imgwidth,imgheight;
	int imagedepth;
	int datasize;
	int itemp[3];
	unsigned char ctemp[3];
	//struct ppmimg * tmpimg = (struct ppmimg*)malloc(sizeof(struct ppmimg));
	//(*simg) = new struct ppmimg;
	
	if((fp=fopen(imagename,"rt"))==NULL){
		exit(1);
	}
	fgets(buff,255,fp);
	while(buff[0]=='#'){
		fgets(buff,255,fp);
	}
	if(buff[0]=='P'){
		sprintf((simg)->magicnumber,"%s",buff);
		simg->magicnumber[2] = '\0';//fgetsは
	}
	fgets(buff,255,fp);
	while(buff[0]=='#'){
		fgets(buff,255,fp);
	}
	sscanf(buff,"%d %d",&imgwidth,&imgheight);
	fgets(buff,255,fp);
	while(buff[0]=='#'){
		fgets(buff,255,fp);
	}
	sscanf(buff,"%d",&imagedepth);
	//fgets(buff,255,fp);
	//while(buff[0]=='#'){
	//	fgets(buff,255,fp);
	//}
	
	simg->iwidth=imgwidth;
	simg->iheight=imgheight;
	simg->depth=imagedepth;

	printf("%d\n",strcmp(simg->magicnumber,"P2"));
	if(strcmp(simg->magicnumber,"P3")==0){
		simg->cmode = 3;
	}else if(strcmp(simg->magicnumber,"P2")==0){
		simg->cmode = 1;
	}
	datasize = (simg->iwidth)*(simg->iheight)*(simg->cmode);
	simg->dat=(unsigned char *)malloc(sizeof(unsigned char)*datasize);
	//free((*simg)->dat);
	if(simg->cmode==3){
		for(int i=0;i<datasize;i+=simg->cmode){
		//	fscanf(fp,"%d %d %d",&((*simg)->dat[i]),&((*simg)->dat[i+1]),&((*simg)->dat[i+2]));	
			//fscanf(fp,"%d",(*simg)->dat + i);
			//fscanf(fp,"%d",(*simg)->dat + i+1);
			//fscanf(fp,"%d",(*simg)->dat + i+2);
			fscanf(fp,"%d %d %d",&(itemp[0]),&(itemp[1]),&(itemp[2]));
			for(int k=0;k<3;k++){
				simg->dat[i+k] = (unsigned char)itemp[k];
			}
			
		}
	}else{
		for(int i=0;i<datasize;i+=simg->cmode){
			//fscanf(fp,"%d",(*simg)->dat + i);	
			fscanf(fp,"%d",&(itemp[0]));
			simg->dat[i] = (unsigned char)itemp[0];
		}
	}
}
コード例 #8
0
ファイル: NN.cpp プロジェクト: BaekYoungBin/UniversityProject
int main(){

	int a,b;
	char c;
	int i;
	int j;
	double dif;
	int col = 0;
	double sum_sq_error = 0 ;
	int epoch=0;
	double pre_avg_sq_error = 0;
	double accuracy = 0;
	double max = 0;
	int num_correct= 0, tmp, k;
	//�ʱ�ȭ
	for(i = 0; i<NLayer; i++){
		for(j = 0; j<MLayerSize; j++){
			s[i][j] = 0;
			f[i][j] = 0;
			delta[i][j] = 0;
		}
	}



	initialization();		// ����ġ ������ �ʱ�ȭ


	FILE *fp, *fp1;
	fp = fopen("traindata.txt", "r");fp1 = fopen("testdata.txt", "r");//�Է½�ȣ ��������
	while(!feof(fp)){
		fscanf(fp, "%d", &a);
		for(i = 0; i<m2; i++){
			if(a == i)	
				d[col][i] = 1;
			else	
				d[col][i] = 0;		
		}	
		fscanf(fp, " %c ", &c);		c = '0';	// $������
		for(i = 0; i<N; i++){
			fscanf(fp, "%d", &b);
			TrainData[col][i] = b;
		}
		col ++;
	}
	col = 0;a = 0;b = 0;
	while(!feof(fp1)) {
		fscanf(fp1, "%d", &a);
		for(i=0; i<m2; i++) {
			if(a==i) 
				Td[col][i]=1;
			else 
				Td[col][i]=0;		
		}
		fscanf(fp1, " %c ", &c);	c = '0';	// $������
		for(i=0; i<N; i++) {
			fscanf(fp1, " %d",  &b);
			TestData[col][i]=b;		
		}
		col++;
	}
	//file input


	do{
		pre_avg_sq_error = avg_sq_error;
	//	printf("pre = %lf\n", pre_avg_sq_error);
		avg_sq_error=0, sum_sq_error=0;
		for(int t=0; t<=N_tr_examples-1; t++){		// �� ������ �Ʒð���
			forward_compute(t);
			backward_compute(t);
			weight_update(t);
		}
		epoch++;
		for(int t = 0; t<=N_tr_examples-1; t++){	// �� ���� �� ��� ���� ���
			// t���� �Ʒÿ����� �̿��Ͽ� �ý����� ����� ���� error�� ����
			forward_compute(t);													//  t ��° �Ʒÿ��� �����Ͽ� ����� ����

			for(i = 0; i<=M[NLayer-1]-1 ; i++){									       // �������� ����� �̿��Ͽ� ������ ����.
				sum_sq_error+=pow((d[t][i]-f[NLayer-1][i]),2);					
			}
		}
		avg_sq_error = sum_sq_error/(N_tr_examples*M[NLayer-1]);						//��� �Ʒ� ���� ���Ͽ� ��� square ������ �����
		printf("%d epoch error rate = %lf\n",epoch,avg_sq_error);

		/*        Fail �κ�, �Ӱ�ġ ���Ϸ� �������� �ʹ� ���� ����� ������ ������ �Ͼ���ϴ�.
		dif = pre_avg_sq_error - avg_sq_error;
		if(dif < 0)
			dif = -dif;
		printf("dif = %lf\n", dif);
		*/

	}while(threshold < avg_sq_error) ;
		//&& (threshold < dif));				//avg_sq_error �� �Ӱ�ġ �����̸� ����, 
	//�Ǵ� ���� epoch ������ avg_sq_error �� �̹� epoch �� avg_sq_error  �� ���̰�       �Ӱ�ġ �����̸� ����


	for(int t = 0; t<=N_te_examples-1; t++){
		// TestData[t], d_te[t] �� input,d�� �ִ´�.
		t_forward_compute(t);
		max=0.;
		for(j=0; j<NLayer; j++) {	
			if(max < f[NLayer-1][j]) {
				max = f[NLayer-1][j];
				tmp = j;
			}
		}
		for(k=0; k<NLayer; k++) {
			if(Td[t][k] == 1 && tmp == k)
				num_correct++;
		}
	}
	accuracy =  (double)num_correct/(double)N_te_examples;
	printf("Accuracy = %lf", accuracy);

	fclose(fp);
	fclose(fp1);
}
コード例 #9
0
unsigned int get_pid_by_name(const char *pro_name)
{
	/*
	 * search /proc/pid/status to find program's name 
	 * and then we can find the pid
	 */
	unsigned int pid = 1; // search start
	FILE *filp = NULL;
	char proc_status[20] = {0};
	char status_info[100] = {0}; //file status information store in this
	char cur_name[100] = {0}; //program's name's max lenght

	unsigned int pid_max = get_sys_max_pid(); //max pid

	while (1) {
		/*
		 * open 1 program's status file, then read data
		 */
		sprintf(proc_status, "/proc/%u/status", pid);
#ifdef DEBUG
		printf("proc_status: %s, led: %d\n", proc_status, strlen(proc_status));
#endif

		filp = fopen(proc_status, "r");
		if (!filp) {
#ifdef DEBUG
			perror("fopen");
#endif
			if (pid >= pid_max) {
				fprintf(stderr, "Can not find pid of program %s\n", pro_name);
				break;
			}
			/*
			 * current pid is no exist, go to search next
			 */
			pid++;
			continue;
		} 
		/*
		 * get one line to sparse by loop
		 */
		while ((!feof(filp)) && (fgets(status_info, 99, filp))) {
			if (sscanf(status_info, "Name: %s", cur_name) == 1) {
				/*
				 * Run here means that we got current program's name,
				 * next what we should do is to compare.
				 */
				if (!strcmp(cur_name, pro_name)) {
					fclose(filp);
					return pid;
				}
				/*
				 * Not match, search next pid.
				 */
				bzero(cur_name, sizeof(cur_name));
				break;

			}
			/*
			 * Didn't scan target, scan next line.
			 */
			bzero(status_info, sizeof(status_info));
		} /* end of one pid */
		pid++;
		fclose(filp);
		bzero(status_info, sizeof(status_info));
	}
	
	return 0; /* Haven't find the pid, return 0 */
}
コード例 #10
0
ファイル: textures.cpp プロジェクト: kriswema/zhlt-linux
// =====================================================================================
//  TEX_InitFromWad
// =====================================================================================
bool            TEX_InitFromWad()
{
    int             i, j;
    wadinfo_t       wadinfo;
    char            szTmpWad[1024]; // arbitrary, but needs to be large.
    char*           pszWadFile;
    const char*     pszWadroot;
    wadpath_t*      currentwad;

    Log("\n"); // looks cleaner

    szTmpWad[0] = 0;
    pszWadroot = getenv("WADROOT");

#ifdef HLCSG_AUTOWAD
    autowad_UpdateUsedWads();
#endif

    // for eachwadpath
    for (i = 0; i < g_iNumWadPaths; i++)
    {
        FILE*           texfile;                           // temporary used in this loop
        bool            bExcludeThisWad = false;

        currentwad = g_pWadPaths[i];
        pszWadFile = currentwad->path;


#ifdef HLCSG_AUTOWAD
        #ifdef _DEBUG
        Log("[dbg] Attempting to parse wad: '%s'\n", pszWadFile);
        #endif

        if (g_bWadAutoDetect && !currentwad->usedtextures)
            continue;

        #ifdef _DEBUG
        Log("[dbg] Parsing wad\n");
        #endif
#endif

        texfiles[nTexFiles] = fopen(pszWadFile, "rb");

        #ifdef SYSTEM_WIN32
        if (!texfiles[nTexFiles])
        {
            // cant find it, maybe this wad file has a hard code drive
            if (pszWadFile[1] == ':')
            {
                pszWadFile += 2;                           // skip past the drive
                texfiles[nTexFiles] = fopen(pszWadFile, "rb");
            }
        }
        #endif

        if (!texfiles[nTexFiles] && pszWadroot)
        {
            char            szTmp[_MAX_PATH];
            char            szFile[_MAX_PATH];
            char            szSubdir[_MAX_PATH];

            ExtractFile(pszWadFile, szFile);

            ExtractFilePath(pszWadFile, szTmp);
            ExtractFile(szTmp, szSubdir);

            // szSubdir will have a trailing separator
            safe_snprintf(szTmp, _MAX_PATH, "%s" SYSTEM_SLASH_STR "%s%s", pszWadroot, szSubdir, szFile);
            texfiles[nTexFiles] = fopen(szTmp, "rb");

            #ifdef SYSTEM_POSIX
            if (!texfiles[nTexFiles])
            {
                // if we cant find it, Convert to lower case and try again
                strlwr(szTmp);
                texfiles[nTexFiles] = fopen(szTmp, "rb");
            }
            #endif
        }

        if (!texfiles[nTexFiles])
        {
            // still cant find it, error out
            Fatal(assume_COULD_NOT_FIND_WAD, "Could not open wad file %s", pszWadFile);
            continue;
        }

        // look and see if we're supposed to include the textures from this WAD in the bsp.
        WadInclude_i it;
        for (it = g_WadInclude.begin(); it != g_WadInclude.end(); it++)
        {
            if (stristr(pszWadFile, it->c_str()))
            {
                Log("Including Wadfile: %s\n", pszWadFile);
                bExcludeThisWad = true;             // wadincluding this one
                s_WadIncludeMap[nTexFiles] = true;
                break;
            }
        }

        if (!bExcludeThisWad)
        {
            Log("Using Wadfile: %s\n", pszWadFile);
            safe_snprintf(szTmpWad, 1024, "%s%s;", szTmpWad, pszWadFile);
        }

        // temp assignment to make things cleaner:
        texfile = texfiles[nTexFiles];

        // read in this wadfiles information
        SafeRead(texfile, &wadinfo, sizeof(wadinfo));

        // make sure its a valid format
        if (strncmp(wadinfo.identification, "WAD2", 4) && strncmp(wadinfo.identification, "WAD3", 4))
        {
            Log(" - ");
            Error("%s isn't a Wadfile!", pszWadFile);
        }

        wadinfo.numlumps        = LittleLong(wadinfo.numlumps);
        wadinfo.infotableofs    = LittleLong(wadinfo.infotableofs);

        // read in lump
        if (fseek(texfile, wadinfo.infotableofs, SEEK_SET))
            Warning("fseek to %d in wadfile %s failed\n", wadinfo.infotableofs, pszWadFile);

        // memalloc for this lump
        lumpinfo = (lumpinfo_t*)realloc(lumpinfo, (nTexLumps + wadinfo.numlumps) * sizeof(lumpinfo_t));

        // for each texlump
        for (j = 0; j < wadinfo.numlumps; j++, nTexLumps++)
        {
            SafeRead(texfile, &lumpinfo[nTexLumps], (sizeof(lumpinfo_t) - sizeof(int)) );  // iTexFile is NOT read from file

            if (!TerminatedString(lumpinfo[nTexLumps].name, MAXWADNAME))
            {
                lumpinfo[nTexLumps].name[MAXWADNAME - 1] = 0;
                Log(" - ");
                Warning("Unterminated texture name : wad[%s] texture[%d] name[%s]\n", pszWadFile, nTexLumps, lumpinfo[nTexLumps].name);
            }

            CleanupName(lumpinfo[nTexLumps].name, lumpinfo[nTexLumps].name);

            lumpinfo[nTexLumps].filepos = LittleLong(lumpinfo[nTexLumps].filepos);
            lumpinfo[nTexLumps].disksize = LittleLong(lumpinfo[nTexLumps].disksize);
            lumpinfo[nTexLumps].iTexFile = nTexFiles;

            if (lumpinfo[nTexLumps].disksize > MAX_TEXTURE_SIZE)
            {
                Log(" - ");
                Warning("Larger than expected texture (%d bytes): '%s'",
                    lumpinfo[nTexLumps].disksize, lumpinfo[nTexLumps].name);
            }

        }

        // AJM: this feature is dependant on autowad. :(
        // CONSIDER: making it standard?
#ifdef HLCSG_AUTOWAD
        {
            double percused = ((float)(currentwad->usedtextures) / (float)(g_numUsedTextures)) * 100;
            Log(" - Contains %i used texture%s, %2.2f percent of map (%d textures in wad)\n",
                currentwad->usedtextures, currentwad->usedtextures == 1 ? "" : "s", percused, wadinfo.numlumps);
        }
#endif

        nTexFiles++;
        hlassume(nTexFiles < MAX_TEXFILES, assume_MAX_TEXFILES);
    }

    //Log("num of used textures: %i\n", g_numUsedTextures);

    // AJM: Tommy suggested i add this warning message in, and  it certianly doesnt
    //  hurt to be cautious. Especially one of the possible side effects he mentioned was svc_bad
    if (nTexFiles > 8)
    {
        Log("\n");
        Warning("More than 8 wadfiles are in use. (%i)\n"
                "This may be harmless, and if no strange side effects are occurring, then\n"
                "it can safely be ignored. However, if your map starts exhibiting strange\n"
                "or obscure errors, consider this as suspect.\n"
                , nTexFiles);
    }

    // sort texlumps in memory by name
    qsort((void*)lumpinfo, (size_t) nTexLumps, sizeof(lumpinfo[0]), lump_sorter_by_name);

    SetKeyValue(&g_entities[0], "wad", szTmpWad);

    Log("\n");
    CheckFatal();
    return true;
}
コード例 #11
0
int main(int argc, char *argv[]) {
	FILE *fp;
	unsigned sbs = 32, s = 0, ibs = 32, i = 0, j, n, m;
	char c;
	char *sb = malloc(sbs);
	unsigned *ib = malloc(ibs * sizeof(unsigned));
	ib[0] = 0;

	if (argc != 2) {
		printf("Usage: %s [FILE]\n", argv[0]);
		return 1;
	}
	fp = fopen(*++argv, "r");
	while ((fscanf(fp, "%d;%d;", &n, &m)) != EOF) {
		unsigned tn = 0, te, ts, tw = 0;
		if (n * m > ibs) {
			ibs = n * m;
			ib = realloc(ib, ibs * sizeof(unsigned));
		}
		while (i < n * m) {
			if (s == sbs) {
				sbs += sbs / 2;
				sb = realloc(sb, sbs);
			}
			if ((c = getc(fp)) == ' ' || c == '\n' || c == EOF) {
				c = '\0';
				if (++i < n * m)
					ib[i] = s + 1;
			}
			sb[s++] = c;
		}
		i = 0;
		j = 1;
		te = m - 1;
		ts = n - 1;
		printf("%s", sb);
		do {
			while (j <= te) {
				printf(" %s", sb + ib[i * m + j]);
				if (j < te)
					j++;
				else
					break;
			}
			i++;
			tn++;
			if (i > ts)
				break;
			while (i <= ts) {
				printf(" %s", sb + ib[i * m + j]);
				if (i < ts)
					i++;
				else
					break;
			}
			j--;
			te--;
			if (j < tw)
				break;
			while (j >= tw) {
				printf(" %s", sb + ib[i * m + j]);
				if (j > tw)
					j--;
				else
					break;
			}
			i--;
			ts--;
			if (i < tn)
				break;
			while (i >= tn) {
				printf(" %s", sb + ib[i * m + j]);
				if (i > tn)
					i--;
				else
					break;
			}
			j++;
			tw++;
		} while (j <= te);
		printf("\n");
		s = 0;
		i = 0;
	}
	free(ib);
	free(sb);
	return 0;
}
コード例 #12
0
ファイル: scpi.c プロジェクト: dirkcgrunwald/iio-oscilloscope
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;
}
コード例 #13
0
ファイル: 22.cpp プロジェクト: alzobnin/hse-cs-prog
 File(const char * name) {
     f = fopen(name, "r");
     if (f == nullptr)
         throw CannotOpenFileException();
 }
コード例 #14
0
ファイル: lfile.cpp プロジェクト: kenjreno/lora3
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;
   }
}
コード例 #15
0
ファイル: lfile.cpp プロジェクト: kenjreno/lora3
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;
}
コード例 #16
0
ファイル: initialization.c プロジェクト: dietmarw/OMCompiler
/*! \fn static int symbolic_initialization(DATA *data)
 *
 *  \param [ref] [data]
 *
 *  \author lochel
 */
static int symbolic_initialization(DATA *data, threadData_t *threadData, long numLambdaSteps)
{
  TRACE_PUSH
  long step;
  int retVal;

  /* initial sample and delay before initial the system */
  initDelay(data, data->simulationInfo->startTime);

  /* initialize all relations that are ZeroCrossings */
  storePreValues(data);
  overwriteOldSimulationData(data);

  if (data->callback->useHomotopy && numLambdaSteps > 1)
  {
    long i;
    char buffer[4096];
    FILE *pFile = NULL;

    modelica_real* realVars = (modelica_real*)calloc(data->modelData->nVariablesReal, sizeof(modelica_real));
    modelica_integer* integerVars = (modelica_integer*)calloc(data->modelData->nVariablesInteger, sizeof(modelica_integer));
    modelica_boolean* booleanVars = (modelica_boolean*)calloc(data->modelData->nVariablesBoolean, sizeof(modelica_boolean));
    modelica_string* stringVars = (modelica_string*) omc_alloc_interface.malloc_uncollectable(data->modelData->nVariablesString * sizeof(modelica_string));
    MODEL_DATA *mData = data->modelData;

    assertStreamPrint(threadData, 0 != realVars, "out of memory");
    assertStreamPrint(threadData, 0 != integerVars, "out of memory");
    assertStreamPrint(threadData, 0 != booleanVars, "out of memory");
    assertStreamPrint(threadData, 0 != stringVars, "out of memory");

    for(i=0; i<mData->nVariablesReal; ++i) {
      realVars[i] = mData->realVarsData[i].attribute.start;
    }
    for(i=0; i<mData->nVariablesInteger; ++i) {
      integerVars[i] = mData->integerVarsData[i].attribute.start;
    }
    for(i=0; i<mData->nVariablesBoolean; ++i) {
      booleanVars[i] = mData->booleanVarsData[i].attribute.start;
    }
    for(i=0; i<mData->nVariablesString; ++i) {
      stringVars[i] = mData->stringVarsData[i].attribute.start;
    }

    if(ACTIVE_STREAM(LOG_INIT))
    {
      sprintf(buffer, "%s_homotopy.csv", mData->modelFilePrefix);
      pFile = fopen(buffer, "wt");
      fprintf(pFile, "%s,", "lambda");
      for(i=0; i<mData->nVariablesReal; ++i)
        fprintf(pFile, "%s,", mData->realVarsData[i].info.name);
      fprintf(pFile, "\n");
    }

    infoStreamPrint(LOG_INIT, 1, "homotopy process");
    for(step=0; step<numLambdaSteps; ++step)
    {
      data->simulationInfo->lambda = ((double)step)/(numLambdaSteps-1);

      if(data->simulationInfo->lambda > 1.0) {
        data->simulationInfo->lambda = 1.0;
      }

      if(0 == step)
        data->callback->functionInitialEquations_lambda0(data, threadData);
      else
        data->callback->functionInitialEquations(data, threadData);

      infoStreamPrint(LOG_INIT, 0, "lambda = %g done", data->simulationInfo->lambda);

      if(ACTIVE_STREAM(LOG_INIT))
      {
        fprintf(pFile, "%.16g,", data->simulationInfo->lambda);
        for(i=0; i<mData->nVariablesReal; ++i)
          fprintf(pFile, "%.16g,", data->localData[0]->realVars[i]);
        fprintf(pFile, "\n");
      }

      if(check_nonlinear_solutions(data, 0) ||
         check_linear_solutions(data, 0) ||
         check_mixed_solutions(data, 0))
        break;

      setAllStartToVars(data);
    }
    messageClose(LOG_INIT);

    if(ACTIVE_STREAM(LOG_INIT))
      fclose(pFile);

    for(i=0; i<mData->nVariablesReal; ++i)
      mData->realVarsData[i].attribute.start = realVars[i];
    for(i=0; i<mData->nVariablesInteger; ++i)
      mData->integerVarsData[i].attribute.start = integerVars[i];
    for(i=0; i<mData->nVariablesBoolean; ++i)
      mData->booleanVarsData[i].attribute.start = booleanVars[i];
    for(i=0; i<mData->nVariablesString; ++i)
      mData->stringVarsData[i].attribute.start = stringVars[i];

    free(realVars);
    free(integerVars);
    free(booleanVars);
    omc_alloc_interface.free_uncollectable(stringVars);
  }
  else
  {
    data->simulationInfo->lambda = 1.0;
    data->callback->functionInitialEquations(data, threadData);
  }
  storeRelations(data);

  /* check for over-determined systems */
  retVal = data->callback->functionRemovedInitialEquations(data, threadData);

  TRACE_POP
  return retVal;
}
コード例 #17
0
static int hostfile_parse(const char *hostfile, opal_list_t* updates,
                          opal_list_t* exclude, bool keep_all)
{
    int token;
    int rc = ORTE_SUCCESS;


    cur_hostfile_name = hostfile;
    
    orte_util_hostfile_done = false;
    orte_util_hostfile_in = fopen(hostfile, "r");
    if (NULL == orte_util_hostfile_in) {
        if (NULL == orte_default_hostfile ||
            0 != strcmp(orte_default_hostfile, hostfile)) {
            /* not the default hostfile, so not finding it
             * is an error
             */
            orte_show_help("help-hostfile.txt", "no-hostfile", true, hostfile);
            rc = ORTE_ERR_SILENT;
            goto unlock;
        }
        /* if this is the default hostfile and it was given,
         * then it's an error
         */
        if (orte_default_hostfile_given) {
            orte_show_help("help-hostfile.txt", "no-hostfile", true, hostfile);
            rc = ORTE_ERR_NOT_FOUND;
            goto unlock;
        }
        /* otherwise, not finding it is okay */
        rc = ORTE_SUCCESS;
        goto unlock;
    }

    while (!orte_util_hostfile_done) {
        token = orte_util_hostfile_lex();

        switch (token) {
        case ORTE_HOSTFILE_DONE:
            orte_util_hostfile_done = true;
            break;

        case ORTE_HOSTFILE_NEWLINE:
            break;

        /*
         * This looks odd, since we have several forms of host-definitions:
         *   hostname              just plain as it is, being a ORTE_HOSTFILE_STRING
         *   IP4s and user@IPv4s
         *   hostname.domain and [email protected]
         */
        case ORTE_HOSTFILE_STRING:
        case ORTE_HOSTFILE_INT:
        case ORTE_HOSTFILE_HOSTNAME:
        case ORTE_HOSTFILE_IPV4:
        case ORTE_HOSTFILE_IPV6:
        case ORTE_HOSTFILE_RELATIVE:
        case ORTE_HOSTFILE_RANK:
            rc = hostfile_parse_line(token, updates, exclude, keep_all);
            if (ORTE_SUCCESS != rc) {
                goto unlock;
            }
            break;

        default:
            hostfile_parse_error(token);
            goto unlock;
        }
    }
    fclose(orte_util_hostfile_in);
    orte_util_hostfile_in = NULL;

unlock:
    cur_hostfile_name = NULL;

    return rc;
}
コード例 #18
0
ファイル: trilib.c プロジェクト: AidHamza/eviltoys
void
LoadTriangleList(char *filename, triangle_t ** pptri, int *numtriangles)
{
    FILE *input;
    float start;
    char name[256], tex[256];
    int i, count, magic;
    tf_triangle tri;
    triangle_t *ptri;
    int iLevel;
    int exitpattern;
    float t;

    t = -FLOAT_START;
    *((unsigned char *)&exitpattern + 0) = *((unsigned char *)&t + 3);
    *((unsigned char *)&exitpattern + 1) = *((unsigned char *)&t + 2);
    *((unsigned char *)&exitpattern + 2) = *((unsigned char *)&t + 1);
    *((unsigned char *)&exitpattern + 3) = *((unsigned char *)&t + 0);

    if ((input = fopen(filename, "rb")) == 0) {
	fprintf(stderr, "reader: could not open file '%s'\n", filename);
	exit(0);
    }

    iLevel = 0;

    fread(&magic, sizeof(int), 1, input);
    if (BigLong(magic) != MAGIC) {
	fprintf(stderr, "File is not a Alias object separated triangle file,"
		" magic number is wrong.\n");
	exit(0);
    }

    ptri = malloc(MAXTRIANGLES * sizeof(triangle_t));

    *pptri = ptri;

    while (feof(input) == 0) {
	fread(&start, sizeof(float), 1, input);
	*(int *)&start = BigLong(*(int *)&start);

	if (*(int *)&start != exitpattern) {
	    if (start == FLOAT_START) {
		/* Start of an object or group of objects. */
		i = -1;
		do {
		    /* There are probably better ways to read a string from */
		    /* a file, but this does allow you to do error checking */
		    /* (which I'm not doing) on a per character basis.      */
		    ++i;
		    fread(&(name[i]), sizeof(char), 1, input);
		} while (name[i] != '\0');

		/*            indent();                                                 */
		/*            fprintf(stdout,"OBJECT START: %s\n",name);                */
		fread(&count, sizeof(int), 1, input);
		count = BigLong(count);
		++iLevel;
		if (count != 0) {
		    /*                indent();                                             */

		    /*                fprintf(stdout,"NUMBER OF TRIANGLES: %d\n",count);    */

		    i = -1;
		    do {
			++i;
			fread(&(tex[i]), sizeof(char), 1, input);
		    } while (tex[i] != '\0');

		    /*                indent();                                             */
		    /*                fprintf(stdout,"  Object texture name: '%s'\n",tex);  */
		}

		/* Else (count == 0) this is the start of a group, and */
		/* no texture name is present. */
	    } else if (start == FLOAT_END) {
		/* End of an object or group. Yes, the name should be */
		/* obvious from context, but it is in here just to be */
		/* safe and to provide a little extra information for */
		/* those who do not wish to write a recursive reader. */
		/* Mia culpa. */
		--iLevel;
		i = -1;
		do {
		    ++i;
		    fread(&(name[i]), sizeof(char), 1, input);
		} while (name[i] != '\0');

		/*            indent();                                                 */
		/*            fprintf(stdout,"OBJECT END: %s\n",name);                  */
		continue;
	    }
	}

	/* read the triangles */
	for (i = 0; i < count; ++i) {
	    int j;

	    fread(&tri, sizeof(tf_triangle), 1, input);
	    ByteSwapTri(&tri);
	    for (j = 0; j < 3; j++) {
		int k;

		for (k = 0; k < 3; k++) {
		    ptri->verts[j][k] = tri.pt[j].p.v[k];
		}
	    }

	    ptri++;

	    if ((ptri - *pptri) >= MAXTRIANGLES)
		Error("Error: too many triangles; increase MAXTRIANGLES\n");
	}
    }

    *numtriangles = ptri - *pptri;

    fclose(input);
}
コード例 #19
0
int Logger::createChannel( const string prefix, const string filename, int newlog )
{
    unsigned int id, fi;
    FILE* fdes;
    string fname;

    try {
        AUTOLOCK(threaded, &maccess);

        // if necessary enlarge storage arrays,
        // before (possibly) inserting a new entry

        if (numChannels == channels.size()) {
            channels.resize(2 * channels.size());
        }
        if (numLogfiles == logfiles.size()) {
            logfiles.resize(2 * logfiles.size());
        }

        // use default file name if non is supplied
        if (filename != "") {
            fname = filename;
        } else {
            fname = logfile;
        }

        // try to find the given channel (see if prefix and logfile identical)
        for (id = 0; id < numChannels; id++) {
            if (channels[id].prefix == prefix &&
                logfiles[channels[id].file_id].fname == fname) {
                return id;
            }
        }

        // try to find a file descriptor, i.e. see if the file is already in use by Logger
        for (fi = 0; fi < numLogfiles; fi++) {
            if (logfiles[fi].fname == fname) {
                channels[numChannels].prefix = prefix;
                channels[numChannels].file_id = fi;
                return numChannels++;
            }
        }

        // if specified get rid of old log file first
        if (newlog == 1) {
            unlink(fname.c_str());
        }

        // else create new logFile and channel entry
        fdes = fopen(fname.c_str(), "a");
        if (fdes == NULL) {
            throw (Error("cannot open log file '%s' for appending", fname.c_str()));
        }
        // set to line buffered
        setvbuf(fdes, NULL, _IOLBF, 0);

        logfiles[numLogfiles].fname = fname;
        logfiles[numLogfiles].file = fdes;

        channels[numChannels].file_id = numLogfiles++;
        channels[numChannels].prefix = prefix;

    } catch (Error &e) {
        throw e;
    }
    return numChannels++;
}
コード例 #20
0
int pdb_parse_files(char* pdb_filename, char* itp_filename, particle_data* atom_data) {
  /*
   * This routine parses the pdb- and itp-file to extract
   * the relevant parameters. These are stored in arrays.
   */

  // Parse pdb-file
  int model = 0;
  char pdb_line[256];
  FILE* pdb_file;
  if ((pdb_file = fopen(pdb_filename,"r")) == NULL) return pdb_ERROR;
#ifdef DEBUG
  printf("### Reading pdb-file \"%s\" ###\n",pdb_filename);
#endif  
  while (fgets(pdb_line, sizeof(pdb_line), pdb_file)) {
    if (strncmp(pdb_line,"MODEL",5) == 0) {
      // read the MODEL identifier
      sscanf(pdb_line,"MODEL %d",&model);
#ifdef DEBUG
      printf("MODEL m=%d\n", model);
#endif
    }
    if ( strncmp(pdb_line,"ATOM",4) == 0) {
      // read all ATOMs
      galloc( (void**) &atom_data->pdb_array_ATOM , (atom_data->pdb_n_particles+1)*sizeof(pdb_ATOM) );
      pdb_ATOM* a = &atom_data->pdb_array_ATOM[atom_data->pdb_n_particles];
      // See http://deposit.rcsb.org/adit/docs/pdb_atom_format.html#ATOM for the meaning of the format string
      sscanf(pdb_line,"ATOM %5d %*4s%*c%*3s%*c%*4d%*c %8f %8f %8f %*6f %*6f %*4s%*2s%*2s",&a->i,&a->x,&a->y,&a->z);
      a->x /= 10.0;
      a->y /= 10.0;
      a->z /= 10.0;
#ifdef DEBUG
      // Print all local variables
      printf("ATOM i=%d x=%f y=%f z=%f\n",a->i,a->x,a->y,a->z);
#endif
      atom_data->pdb_n_particles++;
    }
  }
  fclose(pdb_file);

  // Parse itp-file
  char itp_line[256];
  FILE* itp_file;
  if ((itp_file = fopen(itp_filename,"r")) == NULL) return pdb_ERROR;
#ifdef DEBUG
  printf("### Reading itp-file \"%s\" ###\n",itp_filename);
#endif  
  while (fgets(itp_line, sizeof(itp_line), itp_file)) {
    // get section
    char section[256];
    sscanf(itp_line,"[ %s ]",section);
    // only read non-comment, non-section and non-empty lines
    // TODO: Handling of lines consiting whitespace only (e.g. '\t' and ' ')
    if (itp_line[0] != '[' && itp_line[0] != ';' && itp_line[0] != '\r' && itp_line[0] != '\n') {
      if (strcmp(section,"atoms") == 0) {
        // section [ atoms ]
        galloc( (void**) &atom_data->itp_array_atoms , (atom_data->itp_n_particles+1)*sizeof(pdb_ATOM) );
        itp_atoms* a = &atom_data->itp_array_atoms[atom_data->itp_n_particles];
        // FIXME: no source :( Reverse engineered from the itp-file
        sscanf(itp_line," %d %2s %*d %*s %*s %*d %f %*f ; %*s %*f",&a->i,a->type,&a->charge);
#ifdef DEBUG
        // Print all local variables
        printf("[ atoms ] i=%d type=%s charge=%f\n",a->i,a->type,a->charge);
#endif
        atom_data->itp_n_particles++;
      }
      if (strcmp(section,"atomtypes") == 0) {
        // section [ atomtypes ]
        galloc( (void**) &atom_data->itp_array_atomtypes , (atom_data->itp_n_parameters+1)*sizeof(pdb_ATOM) );
        itp_atomtypes* a = &atom_data->itp_array_atomtypes[atom_data->itp_n_parameters];
        // FIXME: no source :( Reverse engineered from the itp-file
        sscanf(itp_line," %2s %*s %*f %*f %*c %f %f ; %*f %*f",a->type,&a->sigma,&a->epsilon);
#ifdef DEBUG
        // Print all local variables
        printf("[ atomtypes ] name=%s sigma=%f epsilon=%f\n",a->type,a->sigma,a->epsilon);
#endif
        atom_data->itp_n_parameters++;
      }
    }
  }
  fclose(itp_file);

  if (atom_data->pdb_n_particles != atom_data->itp_n_particles) return pdb_ERROR;
  return pdb_SUCCESS;
}
コード例 #21
0
int Logger::moveChannels(string ofname, string nfname, int newlog)
{
    unsigned int id, fi;
    FILE *fdes, *ofdes;

    try {
        AUTOLOCK(threaded, &maccess);

        // close and rename file
        for (fi = 0; fi < numLogfiles; fi++) {
            if (logfiles[fi].fname == ofname) {
                fclose(logfiles[fi].file);
                logfiles[fi].file = NULL;
                break;
            }
        }

        // move all channels over
        for (id = 0; id < numChannels; id++) {
            if (logfiles[channels[id].file_id].fname == ofname) {
                logfiles[channels[id].file_id].fname = nfname;
            }
        }

        // copy old to new (avoid rename function because it can't rename across
        // file systems

        // open old for reading
        ofdes = fopen(ofname.c_str(), "r");
        if (ofdes == NULL) {
            throw (Error("cannot open old log file '%s' for reading", ofname.c_str()));
        }

        // if start new log then delete existing file with new name
        if (newlog == 1) {
            unlink(nfname.c_str());
        }

        // open new file
        fdes = fopen(nfname.c_str(), "a");
        if (fdes == NULL) {
            throw (Error("cannot open log file '%s' for appending", nfname.c_str()));
        }
        // set to line buffered
        setvbuf(fdes, NULL, _IOLBF, 0);

        logfiles[fi].fname = nfname;
        logfiles[fi].file = fdes;

        // copy old stuff
        char buf[4096];
        int sz = 0;

        while ((sz = fread(buf, 1, sizeof(buf), ofdes)) > 0) {
            fwrite(buf, 1, sz, fdes);
        }

        // close and delete old
        fclose(ofdes);
        unlink(ofname.c_str());

    } catch (Error &e) {
        canlog = 0;
        throw e;
    }
    return 0;
}
コード例 #22
0
ファイル: ip.c プロジェクト: innocentboy/myrepository
//common parser method.
//This function takes the file name and get the data as stream.
Hash* parseFileDataStream(const char *fname)
{
    Hash *mp=(Hash *)malloc(sizeof(Hash)*N);
    hashInit(mp);
    int k=0,tempIdx=0,nOctact=0,len=0;
    char temp[4],temp1[4],charcter[4];
    char a[4],b[4],c[4],d[4];
    char ch,prvChar='\0';
    FILE *fptr=fopen(fname, "r");
    if(!fptr){
        perror("falied to open the file..");
        return NULL;
    }
    a[0]=b[0]=c[0]=d[0]='\0';
    while (( fscanf(fptr,"%c",&ch) ) != EOF) {
        if(ch!='.'){
            len++;
            temp[(len-1)%3]=ch;

            if(len<4)
                temp1[len-1]=ch;

            if(len>3)
            {
                tempIdx=(len-1)%3;
            }
        }
        else if(prvChar=='.'&&ch=='.')
        {
            len=0;
            nOctact=0;
        }

        else
        {
            nOctact++;
            temp1[3]='\0';
            if(len<=3)
                tempIdx=0;
            else
                tempIdx=(tempIdx+1)%3;

            int i=tempIdx,j;
            j=0;
            do{

                charcter[j]=temp[i];
                j++;
                if(len>3)
                    i=(i+1)%3;
                else
                    i=(i+1)%len;
            }while(i!=tempIdx);

            if(len>3)
                charcter[3]='\0';
            else
                charcter[len]='\0';
            switch(nOctact)
            {
                case 1:
                    strCopy(a,charcter,0,strlen(charcter)-1);
                    break;
                case 2:
                    strCopy(b,charcter,0,strlen(charcter)-1);
                    break;
                case 3:
                    strCopy(c,charcter,0,strlen(charcter)-1);
                    break;
                case 4:
                    if(len>3)
                        k=3;
                    else
                        k=len;
                    strCopy(d,temp1,0,k-1);
                    generateComb(a,d,b,c,mp);
            }
            if(len>3)
            {
                nOctact=1;
                strCopy(a,charcter,0,strlen(charcter)-1);
            }
            else if(nOctact==4)
            {
                nOctact=3;
                strCopy(a,b,0,strlen(b)-1);
                strCopy(b,c,0,strlen(c)-1);
                strCopy(c,d,0,strlen(d)-1);
            }
            len=0;
        }
        prvChar=ch;
    }

    if(nOctact==3)
    {
        if(len>3)
            k=3;
        else
            k=len;
        strCopy(d,temp1,0,k-1);
        generateComb(a,d,b,c,mp);
    }
    fclose(fptr);
    return mp;
}
コード例 #23
0
ファイル: sys-cmds.c プロジェクト: jsbronder/wrtctl
/*
 * Parses /proc/net/route to grab every triplet of
 * destination, gateway, interface.  Return is a
 * big string with each triplet on a seperate line
 * and ip addresses seperated by colons.
 */
int sys_cmd_route_info(sysh_ctx_t syshc, char *value, uint16_t *out_rc, char **out_str){
    int sys_rc = MOD_OK;
    int rc = 0;
    FILE *fd = NULL;
    char *p;
    char *err = NULL;
    char *realloc_save;
    char *buf = NULL;
    size_t buf_len, buf_used, def_len;
    char line[1024];
    char iface[32];
    char gateway[32];
    char dest[32];

    if ( access(ROUTE_PATH, R_OK) != 0 ){
        sys_rc = EPERM;
        if ( asprintf(out_str, "access:  %s", strerror(errno)) == -1 ){
            err("asprintf: %s\n", strerror(errno));
            *out_str = NULL;
        }
        goto done;
    }

    if ( !(fd = fopen(ROUTE_PATH, "r")) ){
        sys_rc = errno;
        if ( asprintf(out_str, "access: %s", strerror(errno)) == -1 ){
            err("asprintf: %s\n", strerror(errno));
            *out_str = NULL;
        }
        goto done;
    }

    if ( !(buf = malloc(128)) ){
        sys_rc = errno;
        if ( asprintf(out_str, "malloc: %s", strerror(errno)) == -1 ){
            err("asprintf: %s\n", strerror(errno));
            *out_str = NULL;
        }
        goto done;
    }
    buf_len = 128;
    buf_used = 1;
    buf[0] = '\0';

    /*
     * Ignore the first line which is just table names.
     */
    while ( fgetc(fd) != '\n' && feof(fd) == 0 ) {;}

    while ( fgets(line, 1024, fd) ){
        if ( strnlen(line, 1023) >= 1023 ) {
            sys_rc = EINVAL;
            err = "Parse error, line too long";
            break;
        }

        if ( !( p = strtok(line, "\t")) || strnlen(p, 31) >= 31 ){
            sys_rc = EINVAL;
            err = "Parse error, no iface";
            break;
        }
        sprintf(iface, "%s", p);
        
        if ( !( p = strtok(NULL, "\t")) || strnlen(p, 31) >= 31 ){
            sys_rc = EINVAL;
            err = "Parse error, no destination";
            break;
        }
        sprintf(dest, "%s", p);
         
        if ( !( p = strtok(NULL, "\t")) || strnlen(p, 31) >= 31 ){
            sys_rc = EINVAL;
            err = "Parse error, no gateway";
            break;
        }
        sprintf(gateway, "%s", p);

        if ( (rc = ntoip_str(dest)) != 0  || (rc = ntoip_str(gateway)) != 0 ){
            sys_rc = rc;
            if ( asprintf(&err, "ntoip_str: %s", strerror(rc)) == -1 ){
                err = "Parse error, ntoip_str()";
            }
            break;
        }

        /* 'dest:gateway:iface\n' */
        def_len = strlen(dest) + strlen(gateway) + strlen(iface) + 3;
        if ( buf_len <  buf_used + def_len ) {
            realloc_save = realloc(buf, buf_len+128+def_len);
            if ( !realloc_save ){
                sys_rc = errno;
                free(buf);
                if ( asprintf(out_str, "realloc: %s", strerror(errno)) == -1 ){
                    err("asprintf: %s\n", strerror(errno));
                }
                goto done;
            }
            buf = realloc_save;
            buf_len += 128 + def_len;
        }
        
        sprintf( buf+buf_used-1, "%s:%s:%s\n", dest, gateway, iface);
        buf_used += def_len;
    }
   
    if ( err != NULL ){
        if ( asprintf(out_str, "%s\n", err) == -1 ){
            err("asprintf: %s\n", strerror(errno));
            *out_str = NULL;
        }
        goto done;
    } 

    if ( !(*out_str = strdup(buf)) ){
        if ( asprintf(out_str, "strdup: %s", strerror(errno)) == -1 ){
            err("asprintf: %s\n", strerror(errno));
            *out_str = NULL;
        }
        goto done;
    }
    free(buf);
    buf = NULL;
    fclose(fd);
    fd = NULL;

done: 
    if ( fd )
        fclose(fd);
    if ( buf )
        free(buf);
    (*out_rc) = (uint16_t)sys_rc;
    return rc;
}
コード例 #24
0
ファイル: sys-cmds.c プロジェクト: jsbronder/wrtctl
int parse_nameservers(char *path, char **out_str, bool *has_localhost) {
    FILE *fd = NULL;
    char *buf = NULL;
    char *err = NULL;
    size_t buf_len, buf_used, nsl;
    char *p, *realloc_save;
    char line[1024];
    int rc = 0;

    *has_localhost = false;

    if ( !(buf = (char*)malloc(128)) ){
        rc = errno;
        if ( asprintf(out_str, "malloc: %s", strerror(errno)) == -1 ){
            err("asprintf: %s\n", strerror(errno));
            *out_str = NULL;
        }
        goto done;
    }
    buf[0] = '\0';
    buf_used = 1;
    buf_len = 128;

    if ( !(fd = fopen(path, "r")) ){
        rc = errno;
        if ( asprintf(out_str, "fopen(%s): %s", path, strerror(errno)) == -1 ){
            err("asprintf: %s\n", strerror(errno));
            *out_str = NULL;
        }
        goto done;
    }

    while ( fgets(line, 1024, fd) ){
        if ( strnlen(line, 1023) >= 1023 ) {
            rc = EINVAL;
            err = "Parse error, line too long";
            break;
        }
       
        if ( strncmp(line, "nameserver", strlen("nameserver")) )
            continue;

        if ( !( p = strtok(line, "\t ")) 
                || !(p = strtok(NULL, "\t \n"))
                || (nsl = strnlen(p, 31)) >= 31 ) {
            rc = EINVAL;
            err = "Parse error, invalid nameserver";
            break;
        }
       
        if ( buf_len < buf_used + nsl + 1 ){
            realloc_save = realloc(buf, buf_len + 128);
            if ( !realloc_save ){
                rc = errno;
                free(buf);
                if ( asprintf(out_str, "realloc: %s", strerror(errno)) == -1 ){
                    err("asprintf: %s\n", strerror(errno));
                }
                goto done;
            }
            buf = realloc_save;
            buf_len += 128;
        }
        sprintf(buf+buf_used-1, "%s\n", p);
        buf_used += nsl+1;
 
        if ( !strncmp(p, "127.0.0.1", 10) )
            *has_localhost = true;
    }

    if ( err != NULL ){
        if ( asprintf(out_str, "%s\n", err) == -1 ){
            err("asprintf: %s\n", strerror(errno));
            *out_str = NULL;
        }
        goto done;
    } 

    if ( !(*out_str = strdup(buf)) ){
        if ( asprintf(out_str, "strdup: %s", strerror(errno)) == -1 ){
            err("asprintf: %s\n", strerror(errno));
            *out_str = NULL;
        }
        goto done;
    }
    free(buf);
    buf = NULL;
    fclose(fd);
    fd = NULL;

done:
    if ( buf )
        free(buf);
    if ( fd )
        fclose(fd);
    return rc;
} 
コード例 #25
0
int Manager::Report_TCP( Target_Spec *tcp_spec )
{
	int c, scanCount, i, skfd, count = 0;
	char ifname[32];
	FILE *netInfo;
	struct ifreq ifr;

	cout << "Reporting TCP network information..." << endl;
	
	netInfo = fopen("/proc/net/dev", "r");
	assert(netInfo != NULL);
	skfd = socket(PF_INET, SOCK_DGRAM, 0);
	if (skfd < 0) {
		cerr << "Can not create socket in Manager::Report_TCP" << endl;
		return -1;
	}

	// Pull out the first two lines of the file. These two lines contain
	// labels for the columns.
	for (i = 0; i < 2; ++i) {
		do {
			c = getc(netInfo);
		} while ((c != '\n') && (c != EOF));
	}

	for (i = 0; i < MAX_NUM_INTERFACES; ++i) {
		// grab the interface names (if there are leading blanks,
		// then they are removed using the Strip() function)
		scanCount = fscanf(netInfo, "%[^:]: %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d", ifname);
		if (scanCount == EOF) {
			break;
		}
		assert(scanCount == 1);
		Strip(ifname);

		// get ip address for the interface
		strcpy(ifr.ifr_name, ifname);
		ifr.ifr_addr.sa_family = AF_INET;
		if (ioctl(skfd, SIOCGIFADDR, &ifr) == 0) {
			strncpy ( tcp_spec[count].name, inet_ntoa(((struct sockaddr_in *)&(ifr.ifr_addr))->sin_addr), 
					sizeof(tcp_spec[count].name) - 1 );
			tcp_spec[count].type = TCPClientType;	// interface to access a client

			#if _DEBUG
				cout << "   Found " << tcp_spec[count].name << "." << endl;
			#endif
			count++;
		}
		else {
#if _DEBUG
			cerr << "ioctl fail in Manager::Report_TCP()" << endl;
#endif
		}
		// Skip to the next line.
		do {
			c = getc(netInfo);
		} while ((c != '\n') && (c != EOF));
	}
	fclose(netInfo);
	close(skfd);
	// All done.
	cout << "   done." << endl;
	return count;
}
コード例 #26
0
ファイル: star_gen.cpp プロジェクト: cen5bin/acm
void main()
{
	FILE *fp;
	int i, j, k, count;
	
	// I don't use srand
	fp = fopen("star.in","w");
	assert(fp != NULL);
	
/*  -----------------------------   Graph Generation ------------------------  */
	memset(gr, 0, sizeof(gr));
	memset(forbidden, 0, sizeof(forbidden));
	switch(gr_type){
		case GRAPH_TYPE_ANY:
			for(i = 0; i < n; i++)
				for(j = i + 1; j < n; j++)
					gr[i][j] = gr[j][i] = (rand() % 100 < density);

			// Make it connected
			while(1){
				memset(mark, 0, sizeof(mark));
				dfs(0);
				for(i = 0; i < n; i++)
					if(!mark[i]) break;         // unmarked vertex
				if(i == n || mark[i]) break;
				else{
					while(1){					// find a vertex in the set v(1)
						j = rand() % n;
						if(mark[j]) break;
					}
					gr[i][j] = gr[j][i] = 1;	// connect
				}
			}
			break;
		
		case GRAPH_TYPE_TREE:
			memset(mark, 0, sizeof(mark));
			memset(degree, 0 ,sizeof(degree));
			mark[0] = 1;
			for(i = 0; i < n - 1; i++){
				while(1){
					j = rand() % n;
					if(mark[j]) break;
				}
				while(1){
					k = rand() % n;
					if(!mark[k]) break;
				}
				gr[j][k] = gr[k][j] = 1;
				degree[j]++;
				degree[k]++;
				mark[k] = 1;
			}
			for(i = 0; i < n; i++)
				if(degree[i] > 1) forbidden[i] = 1;
			break;
		
		case GRAPH_TYPE_STAR:
			for(i = 1; i < branch; i++){
				gr[0][i] = gr[i][0] = 1;
				last[i-1] = i;
			}
			for(i = branch; i < n; i++){		// connect to the end of a chain
				j = rand() % branch;
				gr[i][last[j]] = gr[last[j]][i] = 1;
				last[j] = i;
			}
			for(i = 0; i < branch; i++)
				forbidden[last[i]] = 1;
			for(i = 0; i < n; i++)
				forbidden[i] = 1 - forbidden[i];
			break;

		case GRAPH_TYPE_RING:
			for(i = 0; i < n; i++)
				gr[i][(i+1)%n] = gr[(i+1)%n][i] = 1;
			break;
	}

	edgecount = 0;
	for(i = 0; i < n; i++)
		for(j = i + 1; j < n; j++)
			if(gr[i][j]) edgecount++;

/*  ----------------  Skills Generation ----------------------  */
	memset(know, 0, sizeof(know));
	memset(skill_ok, 0, sizeof(skill_ok));
	for(i = 0; i < n; i++){
		if(forbidden[i]) continue;
		count = rand() % (skill_upper_bound - skill_lower_bound + 1) + skill_lower_bound;
		for(j = 0; j < count; j++)
			while(1){
				k = rand() % m;
				if(!know[i][k]){
					know[i][k] = 1;
					skill_ok[k] = 1;
					break;
				}
			}

	}
	// Check if any skill is NOT learned by ANYONE
    for(i = 0; i < m; i++)
		if (!skill_ok[i]){
			while(1){
				j = rand() % n;
				if(!forbidden[j]) break;
			}
			know[j][i] = 1;
		}
	
/*  ------------------- Output -----------------------  */
	fprintf(fp, "%d %d\n", n, m);
	for(i = 0; i < n; i++){
		for(j = 0; j < m; j++)
			fprintf(fp, "%d ", know[i][j]);
		fprintf(fp, "\n");
	}
	for(i = 0; i < n; i++){
		j = rand() % 20 + 1;
		k = rand() % 20 + 1;
		fprintf(fp, "%d %d\n", j, k);
	}
	fprintf(fp, "%d\n", edgecount);
	for(i = 0; i < n; i++)
		for(j = i + 1; j < n; j++)
			if(gr[i][j]) fprintf(fp, "%d %d\n", i+1, j+1);

	fclose(fp);
}
コード例 #27
0
ファイル: main.c プロジェクト: kusumi/DragonFlyBSD
int
main(int ac, char **av) {
  int c, i, mntsize;
  char **command;
  struct procfs_status pfs;
  struct ex_types *funcs;
  struct statfs *mntbuf;
  int in_exec = 0;
  char *fname = NULL;
  int sigexit = 0;
  struct trussinfo *trussinfo;

  /* Initialize the trussinfo struct */
  trussinfo = (struct trussinfo *)malloc(sizeof(struct trussinfo));
  if (trussinfo == NULL)
	  errx(1, "malloc() failed");
  bzero(trussinfo, sizeof(struct trussinfo));
  trussinfo->outfile = stderr;

  /* Check where procfs is mounted if it is mounted */
  if ((mntsize = getmntinfo(&mntbuf, MNT_NOWAIT)) == 0)
	  err(1, "getmntinfo");
  for (i = 0; i < mntsize; i++) {
	  if (strcasecmp(mntbuf[i].f_mntfromname, "procfs") == 0) {
		  strlcpy(procfs_path, mntbuf[i].f_mntonname, sizeof(procfs_path));
		  have_procfs = 1;
		  break;
	  }
  }
  if (!have_procfs) {
	  errno = 2;
	  err(1, "You must have a mounted procfs to use truss");
  }

  while ((c = getopt(ac, av, "p:o:S")) != -1) {
    switch (c) {
    case 'p':	/* specified pid */
      trussinfo->pid = atoi(optarg);
      if (trussinfo->pid == getpid()) {
	      /* make sure truss doesn't trace itself */
	      fprintf(stderr, "truss: attempt to self trace: %d\n", trussinfo->pid);
	      exit(2);
      }
      break;
    case 'o':	/* Specified output file */
      fname = optarg;
      break;
    case 'S':	/* Don't trace signals */ 
      trussinfo->flags |= NOSIGS;
      break;
    default:
      usage();
    }
  }

  ac -= optind; av += optind;
  if ((trussinfo->pid == 0 && ac == 0) || (trussinfo->pid != 0 && ac != 0))
    usage();

  if (fname != NULL) { /* Use output file */
    if ((trussinfo->outfile = fopen(fname, "w")) == NULL)
      errx(1, "cannot open %s", fname);
  }

  /*
   * If truss starts the process itself, it will ignore some signals --
   * they should be passed off to the process, which may or may not
   * exit.  If, however, we are examining an already-running process,
   * then we restore the event mask on these same signals.
   */

  if (trussinfo->pid == 0) {	/* Start a command ourselves */
    command = av;
    trussinfo->pid = setup_and_wait(command);
    signal(SIGINT, SIG_IGN);
    signal(SIGTERM, SIG_IGN);
    signal(SIGQUIT, SIG_IGN);
  } else {
    signal(SIGINT, restore_proc);
    signal(SIGTERM, restore_proc);
    signal(SIGQUIT, restore_proc);
  }


  /*
   * At this point, if we started the process, it is stopped waiting to
   * be woken up, either in exit() or in execve().
   */

  Procfd = start_tracing(
      trussinfo->pid, S_EXEC | S_SCE | S_SCX | S_CORE | S_EXIT |
		     ((trussinfo->flags & NOSIGS) ? 0 : S_SIG));
  if (Procfd == -1)
    return 0;

  pfs.why = 0;

  funcs = set_etype(trussinfo);
  /*
   * At this point, it's a simple loop, waiting for the process to
   * stop, finding out why, printing out why, and then continuing it.
   * All of the grunt work is done in the support routines.
   */

  do {
    int val = 0;

    if (ioctl(Procfd, PIOCWAIT, &pfs) == -1)
      warn("PIOCWAIT top of loop");
    else {
      switch(i = pfs.why) {
      case S_SCE:
	funcs->enter_syscall(trussinfo, pfs.val);
	break;
      case S_SCX:
	/*
	 * This is so we don't get two messages for an exec -- one
	 * for the S_EXEC, and one for the syscall exit.  It also,
	 * conveniently, ensures that the first message printed out
	 * isn't the return-from-syscall used to create the process.
	 */

	if (in_exec) {
	  in_exec = 0;
	  break;
	}
	funcs->exit_syscall(trussinfo, pfs.val);
	break;
      case S_SIG:
	fprintf(trussinfo->outfile, "SIGNAL %lu\n", pfs.val);
	sigexit = pfs.val;
	break;
      case S_EXIT:
	fprintf (trussinfo->outfile, "process exit, rval = %lu\n", pfs.val);
	break;
      case S_EXEC:
	funcs = set_etype(trussinfo);
	in_exec = 1;
	break;
      default:
	fprintf (trussinfo->outfile, "Process stopped because of:  %d\n", i);
	break;
      }
    }
    if (ioctl(Procfd, PIOCCONT, val) == -1) {
      if (kill(trussinfo->pid, 0) == -1 && errno == ESRCH)
	break;
      else
	warn("PIOCCONT");
    }
  } while (pfs.why != S_EXIT);
  fflush(trussinfo->outfile);
  if (sigexit) {
    if (sigexit == SIGQUIT)
      exit(sigexit);
    (void) signal(sigexit, SIG_DFL);
    (void) kill(getpid(), sigexit);
  }
  return 0;
}
コード例 #28
0
int main( int argc, char* argv[] )
{
  // ---------------------------------------
  //      command-line option parsing
  // ---------------------------------------
  // Initialize command-line option variables with default values
  char* backup_file_name           = NULL;
  char* main_output_name           = NULL;
  char* neutral_region_output_name = NULL;
  bool best_only = false;
  
  // Define allowed options
  const char * options_list = "hf:o:bn:";
  static struct option long_options_list[] =
  {
    { "help", 0, NULL, 'h' },
    { "file", 1, NULL, 'f' },
    { "output", 1, NULL, 'o' },
    { "best", 0, NULL, 'b' },
    { "neutral", 0, NULL, 'n' },
    { 0, 0, 0, 0 }
  };

  // Get actual values of the command-line options
  int option;
  while ( ( option = getopt_long(argc, argv, options_list, long_options_list, NULL) ) != -1 ) 
  {
    switch ( option ) 
    {
    case 'h' :
      print_help( argv[0] );
      exit( EXIT_SUCCESS );
      break;
    case 'f' :
      backup_file_name = new char[strlen(optarg) + 1];
      sprintf( backup_file_name, "%s", optarg );
      break;
    case 'o' :
      main_output_name = new char[strlen(optarg) + 1];
      sprintf( main_output_name, "%s", optarg );
      break;
    case 'n' :
      neutral_region_output_name = new char[strlen(optarg) + 1];
      sprintf( neutral_region_output_name, "%s", optarg );
      break;
    case 'b' :
      best_only = true;
      break;
    }
  }
  
  // -------------------------------
  //          Initialize
  // -------------------------------
  FILE* main_output           = NULL;
  FILE* neutral_region_output = NULL;
  
  if ( backup_file_name == NULL )
  {
    printf("You must specify a backup file. Please use the option -f or --file.\n");
    exit(EXIT_FAILURE);
  }
  if ( main_output_name != NULL )
  {
    main_output = fopen(main_output_name,"w");
    if ( main_output == NULL)
    {
      fprintf( stderr, "Warning: Could not open file %s.\n", main_output_name );
    }
  }
  if ( neutral_region_output_name != NULL )
  {
    neutral_region_output = fopen(neutral_region_output_name,"w");
    if ( neutral_region_output == NULL)
    {
      fprintf( stderr, "Warning: Could not open file %s.\n", neutral_region_output_name );
    }
  }
  fflush( stderr );

  printf( "Reading backup file <%s>... \n", backup_file_name );
  fflush( stdout );

  // Load the simulation from backup
  ae_common::sim = new ae_experiment();
  ae_common::sim->load_backup( backup_file_name, false, NULL );
  printf("done\n");
  delete [] backup_file_name;

  printf( "Computing phenotypes... \n" );
  fflush( stdout );

  // Evaluate the individuals
  ae_common::pop->evaluate_individuals(ae_common::sim->get_env());
  
  int i = 0;
  int nb_indiv = ae_common::pop->get_nb_indivs();

  // --------------------------------
  //         Parse individuals
  // --------------------------------
  if (best_only)
  {
    ae_individual* best = ae_common::pop->get_best();
    if ( main_output != NULL)           { print_genome_info(best, main_output); }
    if ( neutral_region_output != NULL) { print_neutral_regions(best, neutral_region_output); }
  }
  else
  {
    if (ae_common::pop_structure)
    {
      ae_grid_cell*** _pop_grid = ae_common::pop->get_pop_grid();
      for ( int16_t x = 0 ; x < ae_common::grid_x ; x++ )
      {
        for ( int16_t y = 0 ; y < ae_common::grid_y ; y++ )
        {
          ae_individual* indiv = (_pop_grid[x][y]->get_individual());
	  if ( main_output != NULL)           { print_genome_info(indiv, main_output); }
	  if ( neutral_region_output != NULL) { print_neutral_regions(indiv, neutral_region_output); }
          i++;
        }  
      }
    }
    else
    {
      ae_list_node  * indiv_node = ae_common::pop->get_indivs()->get_first();
      ae_individual * indiv      = NULL;

      while( indiv_node != NULL )
      {
        indiv = (ae_individual *) indiv_node->get_obj();
        if ( main_output != NULL)           { print_genome_info(indiv, main_output); }
	if ( neutral_region_output != NULL) { print_neutral_regions(indiv, neutral_region_output); }
        indiv_node = indiv_node->get_next();
	i++;
      }
    }
  }
  
  if ( main_output != NULL ) { fclose(main_output); }
  if ( neutral_region_output != NULL ) { fclose(neutral_region_output); }

  if ( main_output_name != NULL )           { delete [] main_output_name; }
  if ( neutral_region_output_name != NULL ) { delete [] neutral_region_output_name; }
  
  ae_common::clean();
  
  return EXIT_SUCCESS;
}
コード例 #29
0
ファイル: lib525.c プロジェクト: 0w/moai-dev
int test(char *URL)
{
  int res = 0;
  CURL *curl;
  FILE *hd_src ;
  int hd ;
  int error;
  struct_stat file_info;
  int running;
  char done=FALSE;
  CURLM *m;
  struct timeval ml_start;
  struct timeval mp_start;
  char ml_timedout = FALSE;
  char mp_timedout = FALSE;

  if (!libtest_arg2) {
    fprintf(stderr, "Usage: lib525 [url] [uploadfile]\n");
    return -1;
  }

  /* get the file size of the local file */
  hd = open(libtest_arg2, O_RDONLY) ;
  fstat(hd, &file_info);
  close(hd) ;

  /* get a FILE * of the same file, could also be made with
     fdopen() from the previous descriptor, but hey this is just
     an example! */
  hd_src = fopen(libtest_arg2, "rb");
  if(NULL == hd_src) {
    error = ERRNO;
    fprintf(stderr, "fopen() failed with error: %d %s\n",
            error, strerror(error));
    fprintf(stderr, "Error opening file: %s\n", libtest_arg2);
    return TEST_ERR_MAJOR_BAD;
  }

  if (curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) {
    fprintf(stderr, "curl_global_init() failed\n");
    fclose(hd_src);
    return TEST_ERR_MAJOR_BAD;
  }

  if ((curl = curl_easy_init()) == NULL) {
    fprintf(stderr, "curl_easy_init() failed\n");
    fclose(hd_src);
    curl_global_cleanup();
    return TEST_ERR_MAJOR_BAD;
  }

  /* enable uploading */
  curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);

  /* specify target */
  curl_easy_setopt(curl,CURLOPT_URL, URL);

  /* go verbose */
  curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);

  /* use active FTP */
  curl_easy_setopt(curl, CURLOPT_FTPPORT, "-");

  /* now specify which file to upload */
  curl_easy_setopt(curl, CURLOPT_READDATA, hd_src);

  /* NOTE: if you want this code to work on Windows with libcurl as a DLL, you
     MUST also provide a read callback with CURLOPT_READFUNCTION. Failing to
     do so will give you a crash since a DLL may not use the variable's memory
     when passed in to it from an app like this. */

  /* Set the size of the file to upload (optional).  If you give a *_LARGE
     option you MUST make sure that the type of the passed-in argument is a
     curl_off_t. If you use CURLOPT_INFILESIZE (without _LARGE) you must
     make sure that to pass in a type 'long' argument. */
  curl_easy_setopt(curl, CURLOPT_INFILESIZE_LARGE,
                   (curl_off_t)file_info.st_size);

  if ((m = curl_multi_init()) == NULL) {
    fprintf(stderr, "curl_multi_init() failed\n");
    curl_easy_cleanup(curl);
    curl_global_cleanup();
    fclose(hd_src);
    return TEST_ERR_MAJOR_BAD;
  }

  if ((res = (int)curl_multi_add_handle(m, curl)) != CURLM_OK) {
    fprintf(stderr, "curl_multi_add_handle() failed, "
            "with code %d\n", res);
    curl_multi_cleanup(m);
    curl_easy_cleanup(curl);
    curl_global_cleanup();
    fclose(hd_src);
    return TEST_ERR_MAJOR_BAD;
  }

  ml_timedout = FALSE;
  ml_start = tutil_tvnow();

  while (!done) {
    fd_set rd, wr, exc;
    int max_fd;
    struct timeval interval;

    interval.tv_sec = 1;
    interval.tv_usec = 0;

    if (tutil_tvdiff(tutil_tvnow(), ml_start) >
        MAIN_LOOP_HANG_TIMEOUT) {
      ml_timedout = TRUE;
      break;
    }
    mp_timedout = FALSE;
    mp_start = tutil_tvnow();

    while (res == CURLM_CALL_MULTI_PERFORM) {
      res = (int)curl_multi_perform(m, &running);
      if (tutil_tvdiff(tutil_tvnow(), mp_start) >
          MULTI_PERFORM_HANG_TIMEOUT) {
        mp_timedout = TRUE;
        break;
      }
      if (running <= 0) {
        done = TRUE;
        break;
      }
    }
    if (mp_timedout || done)
      break;

    if (res != CURLM_OK) {
      fprintf(stderr, "not okay???\n");
      break;
    }

    FD_ZERO(&rd);
    FD_ZERO(&wr);
    FD_ZERO(&exc);
    max_fd = 0;

    if (curl_multi_fdset(m, &rd, &wr, &exc, &max_fd) != CURLM_OK) {
      fprintf(stderr, "unexpected failured of fdset.\n");
      res = 189;
      break;
    }

    if (select_test(max_fd+1, &rd, &wr, &exc, &interval) == -1) {
      fprintf(stderr, "bad select??\n");
      res = 195;
      break;
    }

    res = CURLM_CALL_MULTI_PERFORM;
  }

  if (ml_timedout || mp_timedout) {
    if (ml_timedout) fprintf(stderr, "ml_timedout\n");
    if (mp_timedout) fprintf(stderr, "mp_timedout\n");
    fprintf(stderr, "ABORTING TEST, since it seems "
            "that it would have run forever.\n");
    res = TEST_ERR_RUNS_FOREVER;
  }

#ifdef LIB529
  /* test 529 */
  curl_multi_remove_handle(m, curl);
  curl_multi_cleanup(m);
  curl_easy_cleanup(curl);
#else
  /* test 525 */
  curl_multi_remove_handle(m, curl);
  curl_easy_cleanup(curl);
  curl_multi_cleanup(m);
#endif

  fclose(hd_src); /* close the local file */

  curl_global_cleanup();
  return res;
}
コード例 #30
-1
ファイル: supporto.c プロジェクト: igon86/stencil-compiler
void scatter(DATATYPE* local){
	/* puntatore file dei dati */
	FILE* input;
	/* puntatore alla matrice che verra scatterizzata */
	FILE* out;
	/* array di partizioni */
	DATATYPE* partitions[p];
	/* variabile temporanea per la la lettura del file */
	DATATYPE temp;
	/* indici per i cicli for */
	int i,j;
	/* indice di partizione e offset interno */
	int part_index,part_offset;
	/* array per le coordinate */
	part_id result;
	/* matrice su cui scrivo i dati letti da data */
	DATATYPE matrix[M];
	
	/* apertura del file dei dati */
	input = fopen(INPUT_MATRIX,"r");
	
	ec_meno1( input, "Problema nell'apertura del file dei dati\n" );
	ec_null( input, "Problema nell'apertura del file dei dati\n" );
	
#ifdef DEBUG	
	printf("SCATTER: \n");
#endif	
	/* inizializzazione partizioni */
	for(i = 0; i < p; i++ ){
		partitions[i] = malloc(sizeof(DATATYPE)* localsize);
	}
#ifdef DEBUG	
	printf("PARTIZIONI INIZIALIZZATE\n");
#endif		
	for(i=0; i< M; i++){
		/* leggo il prossimo elemento */
		fscanf(input,FORMAT,&temp);
		matrix[i]=temp;
		
		/* creazione delle coordinate*/
		result = offset2partition(dim,lato,s,i);
		
		/* assegnamento*/
		*(partitions[result.part_index]+result.part_offset) = temp;
		
	}/* LOOP i*/
#ifdef DEBUG	
	printf("RIEMPITE LE PARTIZIONI\n");		

	writeMatrix(SCATTER_MATRIX,matrix);
		
	printf("SCRITTA LA MATRICE SU FILE\n");
#endif		
	/* copio gli elementi nella mia partizione locale */
	for (i=0; i < localsize; i++){
		local[i] = *(partitions[0]+i);
	}
	
	/*invio le partizioni agli altri*/
	for (i=1; i < p; i++){
		if( MPI_Send(partitions[i],localsize, MPI_DATATYPE, i, TAG, MPI_COMM_WORLD) != MPI_SUCCESS ){
			fprintf(stderr,"Fallita la MPI_Send verso %d\n",i);
		}
	}
	
#if DEBUG
	printf("SCATTER TERMINATA\n");
#endif
	
}