Esempio n. 1
0
int main(int argc, char** argv)
{
  double d;
  int n = 1;
  if( argc!=2) {
    printf( "usage: program <number of numbers to read>\n");
    return -1;
  }

#ifdef STDIO
    FILE *f;
    f = fopen( "numbers.txt", "r");
    if ( !f) {
      printf( "Cannot open file\n");
      return -1;
}
    VALUES = atoi( argv[1]);

    for ( ; VALUES; --VALUES) {
      fscanf( f,"%lf", &d);
      printf( "%10.5f", d);
#else
      ifstream f( "numbers.txt", ios_base::in);
      if( !f.is_open()) {
          cout << "Cannot open file\n";
          return -1;
      }
    VALUES = atoi( argv[1]);

    for ( ; VALUES; --VALUES) {
      f >> d;
      cout  << std::setw(10)
      << std::setprecision(5)
      << std::setiosflags( ios::showpoint)
      << std::setiosflags( ios::fixed)
      << d;
#endif

    if (n % 5 == 0) {
#ifdef STDIO
      printf("\n");
#else
      cout << '\n';
#endif
    }
  }

#ifdef STDIO
    fclose( f);
#else
    f.close();
#endif

return (EXIT_SUCCESS);
}
Esempio n. 2
0
off_t lseek(int fid, off_t offset, int whence)
{
  off_t rc;
  FILE *file;

#if OS_PARM_CHECK
  /*-------------------------------------------------------------------*/
  /* If the file descriptor is invalid, return error.                  */
  /*-------------------------------------------------------------------*/
  if (fid < 0 || fid >= FOPEN_MAX)
  {
    set_errno(EBADF);
    return -1;
  }
  if (Files[fid].flags & FCB_DIR)
  {
    set_errno(EISDIR);
    return -1;
  }
#endif

  /*-------------------------------------------------------------------*/
  /* Get exclusive access to upper file system.                        */
  /*-------------------------------------------------------------------*/
  semPend(FileSysSem, WAIT_FOREVER);

  /*-------------------------------------------------------------------*/
  /* Return error if file is closed.                                   */
  /*-------------------------------------------------------------------*/
  file = &Files[fid];
  if (file->ioctl == NULL)
  {
    set_errno(EBADF);
    semPost(FileSysSem);
    return -1;
  }

  /*-------------------------------------------------------------------*/
  /* Acquire exclusive access to lower file system.                    */
  /*-------------------------------------------------------------------*/
  file->acquire(file, F_READ | F_WRITE);

  /*-------------------------------------------------------------------*/
  /* Call file system specific FSEEK routine.                          */
  /*-------------------------------------------------------------------*/
  rc = (off_t)file->ioctl(file, FSEEK, (long)offset, whence);

  /*-------------------------------------------------------------------*/
  /* Release exclusive access to file systems and return result.       */
  /*-------------------------------------------------------------------*/
  file->release(file, F_READ | F_WRITE);
  semPost(FileSysSem);
  return rc;
}
Esempio n. 3
0
bool stackToFile(const Common::String &filename, const Variable &from) {
#if 0
	FILE *fp = fopen(filename, saveEncoding ? "wb" : "wt");
	if (!fp) return fatal("Can't create file", filename);

	VariableStack *hereWeAre = from.varData.theStack -> first;

	encode1 = (byte)saveEncoding & 255;
	encode2 = (byte)(saveEncoding >> 8);

	if (saveEncoding) {
		fprintf(fp, "[Custom data (encoded)]\r\n");
		writeStringEncoded(UTF8_CHECKER, fp);
	} else {
		fprintf(fp, "[Custom data (ASCII)]\n");
	}

	while (hereWeAre) {
		if (saveEncoding) {
			switch (hereWeAre -> thisVar.varType) {
				case SVT_STRING:
				fputc(encode1, fp);
				writeStringEncoded(hereWeAre -> thisVar.varData.theString, fp);
				break;

				case SVT_INT:
				// Small enough to be stored as a char
				if (hereWeAre -> thisVar.varData.intValue >= 0 && hereWeAre -> thisVar.varData.intValue < 256) {
					fputc(2 ^ encode1, fp);
					fputc(hereWeAre -> thisVar.varData.intValue, fp);
				} else {
					fputc(1 ^ encode1, fp);
					fp->writeUint32LE(hereWeAre -> thisVar.varData.intValue);
				}
				break;

				default:
				fatal("Can't create an encoded custom data file containing anything other than numbers and strings", filename);
				fclose(fp);
				return false;
			}
		} else {
			char *makeSureItsText = getTextFromAnyVar(hereWeAre -> thisVar);
			if (makeSureItsText == NULL) break;
			fprintf(fp, "%s\n", makeSureItsText);
			delete makeSureItsText;
		}

		hereWeAre = hereWeAre -> next;
	}
	fclose(fp);
#endif
	return true;
}
Esempio n. 4
0
int proc_unix2dos(const wstrings_c & pars)
{
    if (pars.size() < 3) return 0;
    wstr_c pts = pars.get(1); fix_path(pts, FNO_SIMPLIFY);

    if (!dir_present(pts))
    {
        Print(FOREGROUND_RED, "path-to-files not found: %s", pts.cstr()); return 0;
    }

    wstrings_c exts(pars.get(2), '.');

    if (exts.size() == 0)
    {
        Print(FOREGROUND_RED, "no exts defined");
        return 0;
    }


    wstrings_c lines;
    wstrings_c sfiles;
    fill_dirs_and_files(pts, sfiles, lines);


    for (const wstr_c & f : sfiles)
    {
        bool ok = false;
        for (const wstr_c & e : exts)
            if (f.ends(ts::wstr_c(CONSTWSTR(".")).append(e)) || fn_get_name_with_ext(f).equals(e))
            {
                ok = true;
                break;
            }

        if (ok)
        {
            buf_c b;
            b.load_from_disk_file(f);

            for (int i = b.size() - 1; i >= 0; --i)
            {
                if (b.data()[i] == '\r')
                    b.cut(i, 1);
            }

            for (int i = b.size() - 1; i >= 0; --i)
            {
                if (b.data()[i] == '\n')
                    *b.expand(i, 1) = '\r';
            }

            b.save_to_file(f);
        }
    }


    return 0;
}
Esempio n. 5
0
// ctor: input is filename to open.
// only std::ios::in is supported currently.
// if _makeGlobal == TRUE, then the ZipFile is added to the list
// of global zip files.
zppZipArchive::zppZipArchive(const std::string &_fn, std::ios::openmode _mode, bool _makeGlobal)
{
	ourFile = false;
	zipName = _fn;
	canonizePath(zipName);
#ifdef ZPP_INCLUDE_CRYPT
	passwd = NULL;
#endif
	if (_mode & std::ios_base::in) {
		// make sure "binary" mode is selected.
		_mode |= std::ios_base::binary;
#ifdef ZPP_USE_STDIO
                FILE *infile = fopen(zipName.c_str(),"rb");
	        current_pos_v=0;
#else
		std::ifstream *infile = new std::ifstream();
		infile->open(zipName.c_str(),_mode);
#endif
		ourFile = true;
#ifdef ZPP_USE_STDIO
		if (!infile)
			throw zppError("can't open zip file");
#else
		if (infile->fail())
			throw zppError("can't open zip file");
#endif

		str = infile;
	} else {
		throw ("zppZipArchive:: only std::ios::in currently supported.");
	}

	priority = defaultPriority;
	isGlobal = _makeGlobal;

	// build internal data structures
	parseZipDirectory();
}
Esempio n. 6
0
static int writeStdoutHook(struct _reent *ptr, void *cookie, const char *buf, int buf_len) {
	char temp[1024 + 1];

	//if (KprintfFd > 0) sceIoWrite(KprintfFd, buf, buf_len);
	if (RUNNING_ON_EMULATOR) {
		sceIoDevctl("emulator:", EMULATOR_DEVCTL__SEND_OUTPUT, (void *)buf, buf_len, NULL, 0);
	}

	if (buf_len < sizeof(temp)) {
		if (HAS_DISPLAY) {
			memcpy(temp, buf, buf_len);
			temp[buf_len] = 0;

			//Kprintf("%s", temp);
			pspDebugScreenPrintf("%s", temp);
		}
	}
	
	if (stdout_back._write != NULL) {
		return stdout_back._write(ptr, cookie, buf, buf_len);
	} else {
		return buf_len;
	}
}
Esempio n. 7
0
int fcntl(int fid, int cmd, ...)
{
  va_list ap;
  FILE *file;

#if OS_PARM_CHECK
  /*-------------------------------------------------------------------*/
  /* If the file descriptor is invalid, return error.                  */
  /*-------------------------------------------------------------------*/
  if (fid < 0 || fid >= FOPEN_MAX)
  {
    set_errno(EBADF);
    return -1;
  }
#endif

  /*-------------------------------------------------------------------*/
  /* Get exclusive access to upper file system.                        */
  /*-------------------------------------------------------------------*/
  semPend(FileSysSem, WAIT_FOREVER);

  /*-------------------------------------------------------------------*/
  /* Return error if file is closed.                                   */
  /*-------------------------------------------------------------------*/
  file = &Files[fid];
  if (file->ioctl == NULL)
  {
    semPost(FileSysSem);
    set_errno(EBADF);
    return -1;
  }

  /*-------------------------------------------------------------------*/
  /* Based on the command, execute the right instructions.             */
  /*-------------------------------------------------------------------*/
  switch (cmd)
  {
    case F_DUPFD:
    {
      /*---------------------------------------------------------------*/
      /* Use the va_arg mechanism to get the argument.                 */
      /*---------------------------------------------------------------*/
      va_start(ap, cmd);
      fid = va_arg(ap, int);
      va_end(ap);

#if OS_PARM_CHECK
      /*---------------------------------------------------------------*/
      /* If the file descriptor is invalid, return error.              */
      /*---------------------------------------------------------------*/
      if (fid < 0 || fid >= FOPEN_MAX)
      {
        semPost(FileSysSem);
        set_errno(EINVAL);
        return -1;
      }
#endif
      /*---------------------------------------------------------------*/
      /* Look for free file control block identifier >= fid.           */
      /*---------------------------------------------------------------*/
      for (;;)
      {
        FILE *file2 = &Files[fid];

        /*-------------------------------------------------------------*/
        /* Check if file control block is free.                        */
        /*-------------------------------------------------------------*/
        if (file2->ioctl == NULL)
        {
          /*-----------------------------------------------------------*/
          /* Copy previous file control block to new one.              */
          /*-----------------------------------------------------------*/
          *file2 = *file;

          /*-----------------------------------------------------------*/
          /* Acquire exclusive access to lower file system.            */
          /*-----------------------------------------------------------*/
          file2->acquire(file2, F_READ | F_WRITE);

          /*-----------------------------------------------------------*/
          /* Call file system specific DUP routine.                    */
          /*-----------------------------------------------------------*/
          file2->ioctl(file2, DUP);

          /*-----------------------------------------------------------*/
          /* Release exclusive access to lower file system.            */
          /*-----------------------------------------------------------*/
          file2->release(file2, F_READ | F_WRITE);
          break;
        }

        /*-------------------------------------------------------------*/
        /* If none are free, set errno and break.                      */
        /*-------------------------------------------------------------*/
        if (++fid >= FOPEN_MAX)
        {
          set_errno(EMFILE);
          fid = -1;
          break;
        }
      }

      /*---------------------------------------------------------------*/
      /* Release access to upper file system and return result.        */
      /*---------------------------------------------------------------*/
      semPost(FileSysSem);
      return fid;
    }

    case F_SETFL:
    {
      int oflag, r_val;

      /*---------------------------------------------------------------*/
      /* Acquire exclusive access to lower file system.                */
      /*---------------------------------------------------------------*/
      file->acquire(file, F_READ | F_WRITE);

      /*---------------------------------------------------------------*/
      /* Use the va_arg mechanism to get the argument.                 */
      /*---------------------------------------------------------------*/
      va_start(ap, cmd);
      oflag = va_arg(ap, int);
      va_end(ap);

      /*---------------------------------------------------------------*/
      /* Call specific ioctl to set flag.                              */
      /*---------------------------------------------------------------*/
      r_val = (int)file->ioctl(file, SET_FL, oflag);

      /*---------------------------------------------------------------*/
      /* Release exclusive access to lower file system.                */
      /*---------------------------------------------------------------*/
      file->release(file, F_READ | F_WRITE);

      /*---------------------------------------------------------------*/
      /* Release access to upper file system and return result.        */
      /*---------------------------------------------------------------*/
      semPost(FileSysSem);
      return r_val;
    }

    case F_GETFL:
    {
      int r_val;

      /*---------------------------------------------------------------*/
      /* Acquire exclusive access to lower file system.                */
      /*---------------------------------------------------------------*/
      file->acquire(file, F_READ);

      /*---------------------------------------------------------------*/
      /* Call specific ioctl to get flag.                              */
      /*---------------------------------------------------------------*/
      r_val = (int)file->ioctl(file, GET_FL);

      /*---------------------------------------------------------------*/
      /* Release exclusive access to lower file system.                */
      /*---------------------------------------------------------------*/
      file->release(file, F_READ);

      /*---------------------------------------------------------------*/
      /* Release access to upper file system and return result.        */
      /*---------------------------------------------------------------*/
      semPost(FileSysSem);
      return r_val;
    }
  }

  /*-------------------------------------------------------------------*/
  /* An unsupported command was requested.                             */
  /*-------------------------------------------------------------------*/
  set_errno(EINVAL);
  semPost(FileSysSem);
  return -1;
}
    void parseObjFile(const char* objPath, 
        std::vector<glm::vec3>& vertices, std::vector<glm::vec2>& texcoords,
        std::vector<glm::vec3>& normals, std::vector<GLuint>& vertIndices,
        std::vector<GLuint>& texIndices, std::vector<GLuint>& normIndices) {
#if (defined USE_FSCANF || defined USE_FGETS)
		GLchar buf[BUFSIZE];
        FILE* fp;

        // in Win/VS2010, position from ftell after fopen in text mode 
        // is not accurate (due to translation of newlines)
        if ((NULL == objPath) || (NULL == (fp = fopen(objPath, "rb")))) {
            return;
        }
#ifdef USE_FSCANF
        while (EOF != fscanf(fp, "%s", buf)) {
#else	// USE_FGETS
        while (NULL != fgets(buf, sizeof(buf), fp)) {
#endif
#else	// USE_GETLINE
		GLchar* buf;
        std::string str;
        std::ifstream fp(objPath);

        if (!fp.is_open()) {
            return;
        }
        while (fp.good()) {
            std::getline(fp, str);
#endif
        	GLint res = 0;

#ifdef USE_GETLINE
			buf = (GLchar*)str.c_str();
#endif

            switch (buf[0]) {
                case 'v':
#if (defined USE_FGETS || defined USE_GETLINE)
					if (' ' == buf[1]) {
#else	// USE_FSCANF
                    if (1 == strlen(buf)) {
#endif
                        glm::vec3 vert;
#if (defined USE_FGETS || defined USE_GETLINE)
                        res = sscanf(buf, "v %f %f %f",
#else	// USE_FSCANF
                        res = fscanf(fp, "%f %f %f\n", 
#endif
                        	&vert.x, &vert.y, &vert.z);
                        if (DIM3 != res) {
                            fprintf(stderr, "Incorrect vert matches on sscanf\n");
                        }
                        vertices.push_back(vert);
                    } else if ('t' == buf[1]) {
                        glm::vec2 tex;
#if (defined USE_FGETS || defined USE_GETLINE)
                        res = sscanf(buf, "vt %f %f", 
#else	// USE_FSCANF
                        res = fscanf(fp, "%f %f\n", 
#endif
                        	&tex.x, &tex.y);
                        if (DIM2 != res) {
                            fprintf(stderr, "Incorrect tex matches on sscanf\n");
                        }
                        texcoords.push_back(tex);
                    }  else if ('n' == buf[1]) {
                        glm::vec3 norm;
#if (defined USE_FGETS || defined USE_GETLINE)
                        res = sscanf(buf, "vn %f %f %f", 
#else	// USE_FSCANF
                        res = fscanf(fp, "%f %f %f\n", 
#endif
                        	&norm.x, &norm.y, &norm.z);
                        if (DIM3 != res) {
                            fprintf(stderr, "Incorrect norm matches on sscanf\n");
                        }
                        normals.push_back(norm);
                    }
                    break;
                case 'f':
                    GLuint vertsIdx[VERTS_FACE], normsIdx[VERTS_FACE],
                    	texIdx[VERTS_FACE] = { 1, 1, 1 };
                    
#if (defined USE_FGETS || defined USE_GETLINE)
	                res = sscanf(buf, "f %d/%d/%d %d/%d/%d %d/%d/%d", 
#else	// USE_FSCANF
                    // ensure fopen with binary NOT text mode for Win/VS2010
                    long posPtr = ftell(fp);	// get current stream pos
	                res = fscanf(fp, "%d/%d/%d %d/%d/%d %d/%d/%d\n", 
#endif
	                	&vertsIdx[0], &texIdx[0], &normsIdx[0], 
	                	&vertsIdx[1], &texIdx[1], &normsIdx[1],
	                	&vertsIdx[2], &texIdx[2], &normsIdx[2]);
					if (RES_VertTexNorm != res) {
#if (defined USE_FGETS || defined USE_GETLINE)
		                res = sscanf(buf, "f %d//%d %d//%d %d//%d", 
#else	// USE_FSCANF
						fseek(fp, posPtr, SEEK_SET);	// reset stream pos
		                res = fscanf(fp, "%d//%d %d//%d %d//%d\n", 
#endif
		                	&vertsIdx[0], &normsIdx[0], &vertsIdx[1], 
		                    &normsIdx[1], &vertsIdx[2], &normsIdx[2]);
					}
Esempio n. 9
0
int
do_import(std::string file, int sorted, uint_t limit, 
          int &rnadded, int &rnlines) {
#if defined USE_CXX_IO
    std::ifstream fin(file.c_str());
#else
    FILE *fin = fopen(file.c_str(), "r");
#endif

    int fd = open(file.c_str(), O_RDONLY);

    // Potential race condition + not checking for return value
    if_length = file_size(file.c_str());

    DCERR("handle_import::file:"<<file<<endl);

    if (!fin || !fd) {
        return -IMPORT_FILE_NOT_FOUND;
    }
    else {
        building = true;
        int nlines = 0;
        int foffset = 0;

        if (if_mmap_addr) {
            munmap(if_mmap_addr, if_length);
        }

        // mmap() the input file in
        if_mmap_addr = (char*)mmap(NULL, if_length, PROT_READ, MAP_SHARED, fd, 0);
        if (!if_mmap_addr) {
            fclose(fin);
            close(fd);
            return -IMPORT_FILE_NOT_FOUND;
        }

        pm.repr.clear();
        char buff[INPUT_LINE_SIZE];

        while (
#if defined USE_CXX_IO
               fin
#else
            !feof(fin)
#endif
               && limit--) {

            buff[0] = '\0';

#if defined USE_CXX_IO
            fin.getline(buff, INPUT_LINE_SIZE);
            const int llen = fin.gcount();
            buff[INPUT_LINE_SIZE - 1] = '\0';
#else
            char *got = fgets(buff, INPUT_LINE_SIZE, fin);
            if (!got) {
                break;
            }
            const int llen = strlen(buff);
            if (llen && buff[llen-1] == '\n') {
                buff[llen-1] = '\0';
            }
#endif

            ++nlines;

            int weight = 0;
            std::string phrase;
            StringProxy snippet;
            InputLineParser(if_mmap_addr, foffset, buff, &weight, &phrase, &snippet).start_parsing();

            foffset += llen;

            if (!phrase.empty()) {
                str_lowercase(phrase);
                DCERR("Adding: "<<weight<<", "<<phrase<<", "<<std::string(snippet)<<endl);
                pm.insert(weight, phrase, snippet);
            }
        }

        fclose(fin);
        pm.finalize(sorted);
        vui_t weights;
        for (size_t i = 0; i < pm.repr.size(); ++i) {
            weights.push_back(pm.repr[i].weight);
        }
        st.initialize(weights);

        rnadded = weights.size();
        rnlines = nlines;

        building = false;
    }

    return 0;
}
Esempio n. 10
0
void
processCCO(SnapConConMesg *cco) {
  int   *contigGapToUngap   = NULL;
  int    contigLengthGapped = strlen(cco->consensus);
  int    contigLengthUngap  = 0;
  int    i = 0, j = 0;
  int    isDegenerate = 0;

  //  By definition, a degenerate contig has one unitig and is unplaced.
  //  In reality, those two conditions always occur together.
  //
  FILE  *len = ctglen;
  FILE  *frg = frgctg;
  FILE  *utg = utgctg;
  FILE  *var = varctg;

  if ((cco->placed == AS_UNPLACED) && (cco->num_unitigs == 1)) {
    isDegenerate = 1;
    len = deglen;
    frg = frgdeg;
    utg = utgdeg;
    var = vardeg;
  }


  contigGapToUngap = (int *)safe_calloc(contigLengthGapped + 1, sizeof(int));

  contigGapToUngap[0] = 0;

  for (i=0; i<contigLengthGapped; i++) {
    if (cco->consensus[i] != '-')
      contigLengthUngap++;
    contigGapToUngap[i+1] = contigLengthUngap;
  }

  fprintf(len, "%s\t%d\n",
          AS_UID_toString(cco->eaccession),
          contigLengthUngap);

  if (isDegenerate == 0)
    fprintf(ctginf, "%s\t%d\t%d\t%d\t%d\n",
            AS_UID_toString(cco->eaccession),
            contigLengthUngap,
            cco->num_unitigs,
            cco->num_pieces,
            cco->num_vars);
  else
    fprintf(deginf, "%s\t%d\t%d\t%d\t%d\t%s\t%f\t%f\n",
            AS_UID_toString(cco->eaccession),
            contigLengthUngap,
            cco->num_unitigs,
            cco->num_pieces,
            cco->num_vars,
            AS_UID_toString(cco->unitigs[0].eident),
            covStat[cco->unitigs[0].eident],
            microHet[cco->unitigs[0].eident]);

  uid2iid[cco->eaccession] = cco->iaccession;

  if (ctgInfoMax <= cco->iaccession) {
    ctgInfoMax *= 2;
    ctgInfo     = (ctgInfo_t *)safe_realloc(ctgInfo, ctgInfoMax * sizeof(ctgInfo_t));
  }
  ctgInfo[cco->iaccession].len = contigLengthUngap;

  //  VAR/variants
  for (i=0; i<cco->num_vars; i++) {
    IntMultiVar *v = cco->vars + i;

    int  bgn = contigGapToUngap[v->position.bgn];
    int  end = contigGapToUngap[v->position.end];

    fprintf(var, "%s\t%s\t%d\t%d\t%d\t%d\t%d\t%d\t%s\t%s\t%s\n",
            v->enc_var_seq,
            AS_UID_toString(cco->eaccession),
            bgn, end,
            v->num_reads,
            v->num_alleles_confirmed,
            v->min_anchor_size,
            v->var_length,
            v->enc_num_reads,
            v->enc_weights,
            v->enc_read_ids);
  }

  //  Remember what fragments were placed.  This is used to ignore
  //  some fragments when reporting unplaced surrogate fragments.

  set<AS_UID>  placed;

  //  MPS/fragments
  for (i=0; i<cco->num_pieces; i++) {
    int  bgn = contigGapToUngap[cco->pieces[i].position.bgn];
    int  end = contigGapToUngap[cco->pieces[i].position.end];
    char ori = ORIF;

    //  If bgn == end, then the fragment fell entirely within a gap.

    if (cco->pieces[i].position.bgn > cco->pieces[i].position.end) {
      ori = ORIR;
      end = contigGapToUngap[cco->pieces[i].position.bgn];
      bgn = contigGapToUngap[cco->pieces[i].position.end];
    }

    fprintf(frg, "%s\t%s\t%d\t%d\t%c\n",
            AS_UID_toString(cco->pieces[i].eident),
            AS_UID_toString(cco->eaccession),
            bgn, end, ori);

    if (writeUnplaced)
      placed.insert(cco->pieces[i].eident);
  }

  //  UPS/unitigs
  for (i=0; i<cco->num_unitigs; i++) {
    int  bgn = contigGapToUngap[cco->unitigs[i].position.bgn];
    int  end = contigGapToUngap[cco->unitigs[i].position.end];
    char ori = ORIF;

    //  If this is a SURROGATE UNITIG, report "fraguid unitiguid contiguid"

    if (cco->unitigs[i].position.bgn > cco->unitigs[i].position.end) {
      ori = ORIR;
      end = contigGapToUngap[cco->unitigs[i].position.bgn];
      bgn = contigGapToUngap[cco->unitigs[i].position.end];
    }

    if (isDegenerate == 0)
      fprintf(utg, "%s\t%s\t%d\t%d\t%c\t%s\n",
              AS_UID_toString(cco->unitigs[i].eident),
              AS_UID_toString(cco->eaccession),
              bgn, end, ori,
              decodeUnitigType(cco->unitigs[i].type));
    else
      fprintf(utg, "%s\t%s\t%d\t%d\t%c\n",
              AS_UID_toString(cco->unitigs[i].eident),
              AS_UID_toString(cco->eaccession),
              bgn, end, ori);

    //  unplaced surrogate fragments

    if ((writeUnplaced) && (surrogateUnitigFrags.count(cco->unitigs[i].eident) > 0)) {
      vector<surFrag_t>  &frg = surrogateUnitigFrags[cco->unitigs[i].eident];

      for (uint32 ii=0; ii<frg.size(); ii++) {
        char const *status = "unplaced";

        if (placed.count(frg[ii].id) > 0) {
          //  Read already placed.
          //continue;
          status = "resolved";
        }

        int32  frgbgn = frg[ii].bgn + bgn;
        int32  frgend = frg[ii].end + bgn;

        if (ori == ORIR) {
          frgbgn = end - frg[ii].bgn;
          frgend = end - frg[ii].end;
        }

        if (frgbgn < frgend) {
          fprintf(sfgctg, "%s\t%s\t%d\t%d\t%c\t%s\t%s\n",
                  AS_UID_toString(frg[ii].id),
                  AS_UID_toString(cco->eaccession),
                  contigGapToUngap[frgbgn],
                  contigGapToUngap[frgend],
                  ORIF,
                  status,
                  AS_UID_toString(cco->unitigs[i].eident));
        } else {
          fprintf(sfgctg, "%s\t%s\t%d\t%d\t%c\t%s\t%s\n",
                  AS_UID_toString(frg[ii].id),
                  AS_UID_toString(cco->eaccession),
                  contigGapToUngap[frgend],
                  contigGapToUngap[frgbgn],
                  ORIR,
                  status,
                  AS_UID_toString(cco->unitigs[i].eident));
        }
      }
    }
  }

  safe_free(contigGapToUngap);
}
Esempio n. 11
0
int creatn(const char *path, mode_t mode, size_t size)
{
  int rv = -1;
  void *dir;
  FILE *file;
#if !_PATH_NO_TRUNC
  char trunc_path[PATH_MAX + 1];
#endif

#if OS_PARM_CHECK
  /*-------------------------------------------------------------------*/
  /* If path is NULL, return -1.                                       */
  /*-------------------------------------------------------------------*/
  if (path == NULL)
  {
    set_errno(EFAULT);
    return -1;
  }
#endif

  /*-------------------------------------------------------------------*/
  /* Acquire exclusive access to upper file system.                    */
  /*-------------------------------------------------------------------*/
  semPend(FileSysSem, WAIT_FOREVER);

  /*-------------------------------------------------------------------*/
  /* Find a free file control block and initialize it.                 */
  /*-------------------------------------------------------------------*/
  for (file = &Files[0]; file->ioctl; ++file)
  {
    /*-----------------------------------------------------------------*/
    /* If none are free, return error.                                 */
    /*-----------------------------------------------------------------*/
    if (file == &Files[FOPEN_MAX - 1])
    {
      set_errno(EMFILE);
      semPost(FileSysSem);
      return -1;
    }
  }
  FsInitFCB(file, FCB_FILE);

  /*-------------------------------------------------------------------*/
  /* Ensure path is valid.                                             */
  /*-------------------------------------------------------------------*/
  dir = FSearch(file, &path, PARENT_DIR);
  if (dir == NULL)
    goto end;

  /*-------------------------------------------------------------------*/
  /* If path too long, return error if no truncation, else truncate.   */
  /*-------------------------------------------------------------------*/
  if (strlen(path) > PATH_MAX)
  {
#if _PATH_NO_TRUNC
    set_errno(ENAMETOOLONG);
    goto end;
#else
    strncpy(trunc_path, path, PATH_MAX);
    trunc_path[PATH_MAX] = '\0';
    path = trunc_path;
#endif
  }

  /*-------------------------------------------------------------------*/
  /* Acquire exclusive access to lower file system.                    */
  /*-------------------------------------------------------------------*/
  file->acquire(file, F_READ | F_WRITE);

  /*-------------------------------------------------------------------*/
  /* Call file system specific CREATN routine.                         */
  /*-------------------------------------------------------------------*/
  rv = (int)file->ioctl(file, CREATN, path, mode, size, dir);

  /*-------------------------------------------------------------------*/
  /* Release exclusive access to lower file system.                    */
  /*-------------------------------------------------------------------*/
  file->release(file, F_READ | F_WRITE);

  /*-------------------------------------------------------------------*/
  /* Free control block if error, else set return value.               */
  /*-------------------------------------------------------------------*/
end:
  if (rv == -1)
    file->ioctl = NULL;
  else
    rv = file - &Files[0];

  /*-------------------------------------------------------------------*/
  /* Release exclusive access to upper file system and return result.  */
  /*-------------------------------------------------------------------*/
  semPost(FileSysSem);
  return rv;
}
Esempio n. 12
0
void VmBase::refresh_most()
{
    vm_ids_.clear();
    stable_vmthread_id_to_vm_id_.clear();
    name_.clear();
    uuid_.clear();
    vsocket_num_.clear();
    vcore_num_.clear();
    vhpthread_num_.clear();
    total_mem_size_.clear();

    string cmd = "ps -C " + vm_cmd_ + " -wwo etime=,pid=,args=";
    time_t cur_time;
    time(&cur_time);
    FILE* data = popen(cmd.c_str(), "r");

    string pid;
    string start_timestamp;
    vector<string> args;
    string tmp_str;
    while(fgets(buf_.get(), BUF_SIZE, data))
    {
        args.clear();
        istringstream is(buf_.get());
        is >> start_timestamp;

        long long days = 0;
        long long  hours = 0;
        long long  minutes = 0;
        long long  seconds = 0;
        time_t start_time;
        if (count(start_timestamp.begin(), start_timestamp.end(), '-') > 0)
            sscanf(start_timestamp.c_str(), "%lld-%lld:%lld:%lld", &days, &hours, &minutes, &seconds);
        else if (count(start_timestamp.begin(), start_timestamp.end(), ':') == 2)
            sscanf(start_timestamp.c_str(), "%lld:%lld:%lld", &hours, &minutes, &seconds);
        else if (count(start_timestamp.begin(), start_timestamp.end(), ':') == 1)
            sscanf(start_timestamp.c_str(), "%lld:%lld", &minutes, &seconds);
        start_time = cur_time - (((days * 24 + hours) * 60 + minutes) * 60 + seconds);

        is >> pid;
        while(is)
        {
            is >> tmp_str;
            args.push_back(tmp_str);
        }

        //add vm_ids
        VmId vm_id(start_time, stoull(pid));
        vm_ids_.insert(vm_id);

        //add name
        string name = "";
        auto name_iter = find(args.begin(), args.end(), "-name");
        if (name_iter != args.end())
        {
            ++name_iter;
            name = *name_iter;
        }
        else
        {
            //TODO throw //because of cgroup need it
        }
        name_[vm_id] = name;

        //add uuid
        string uuid = "";
        auto uuid_iter = find(args.begin(), args.end(), "-uuid");
        if (uuid_iter != args.end())
        {
            ++uuid_iter;
            uuid = *uuid_iter;
        }
        uuid_[vm_id] = uuid;

        //add vsocket vcore vhpthread
        auto iter = find(args.begin(), args.end(), "-smp");
        if (iter != args.end())
        {
            ++iter;
            vector<string> ops;
            str_tools::split(*iter, ',', ops);
            for(auto& op : ops)
            {
                vector<string> data;
                str_tools::split(op, '=', data);
                if (data.size() == 2) {
                    if(data[0] == "sockets")
                        vsocket_num_[vm_id] = stoi(data[1]);
                    else if(data[0] == "cores")
                        vcore_num_[vm_id] = stoi(data[1]);
                    else if(data[0] == "threads")
                        vhpthread_num_[vm_id] = stoi(data[1]);
                }
            }
        }

        //add total_mem_size
        int size = -1;
        auto size_iter = find(args.begin(), args.end(), "-m");
        if (size_iter != args.end())
        {
            ++size_iter;
            size = stoi(*size_iter);
        }
        total_mem_size_[vm_id] = size;
    }
    pclose(data);
}
Esempio n. 13
0
int write(int fid, const void *buf, unsigned int nbytes)
{
  int written;
  FILE *file;

#if OS_PARM_CHECK
  /*-------------------------------------------------------------------*/
  /* Ensure file descriptor is valid.                                  */
  /*-------------------------------------------------------------------*/
  if (fid < 0 || fid >= FOPEN_MAX)
  {
    set_errno(EBADF);
    return -1;
  }

  /*-------------------------------------------------------------------*/
  /* Return error if buffer pointer is invalid.                        */
  /*-------------------------------------------------------------------*/
  if (buf == NULL)
  {
    Files[fid].errcode = EFAULT;
    set_errno(EFAULT);
    return -1;
  }
#endif

  /*-------------------------------------------------------------------*/
  /* Acquire exclusive write access to stream.                         */
  /*-------------------------------------------------------------------*/
  file = &Files[fid];
  file->acquire(file, F_WRITE);

  /*-------------------------------------------------------------------*/
  /* Return error if file is closed.                                   */
  /*-------------------------------------------------------------------*/
  if (file->ioctl == NULL)
  {
    set_errno(EBADF);
    file->release(file, F_WRITE);
    return -1;
  }

  /*-------------------------------------------------------------------*/
  /* Call file system specific write routine.                          */
  /*-------------------------------------------------------------------*/
  written = file->write(file, buf, nbytes);

  /*-------------------------------------------------------------------*/
  /* Set file's errno if less than requested number was written.       */
  /*-------------------------------------------------------------------*/
  if (written < (int)nbytes)
  {
    file->errcode = get_errno();
    if (written == 0)
      written = -1;
  }

  /*-------------------------------------------------------------------*/
  /* Release exclusive write access to stream.                         */
  /*-------------------------------------------------------------------*/
  file->release(file, F_WRITE);

  /*-------------------------------------------------------------------*/
  /* Return -1 or actual number of bytes read.                         */
  /*-------------------------------------------------------------------*/
  return written;
}
Esempio n. 14
0
int
ACE_TMAIN (int argcw, ACE_TCHAR *argvw[])
{
  CORBA::ORB_var orb_var;
  try
    {
      Catior_i catior_impl;
      orb_var =  CORBA::ORB_init (argcw, argvw);
      CORBA::Boolean b = false;
      CORBA::Boolean have_argument = false;
      int opt;

      ACE_Get_Opt get_opt (argcw, argvw, ACE_TEXT ("f:n:x"));

      while ((opt = get_opt ()) != EOF)
        {
          // some arguments have been supplied
          have_argument = 1;
          switch (opt)
            {
            case 'n':
              {
                //  Read the CosName from the NamingService convert the
                //  object_ptr to a CORBA::String_var via the call to
                //  object_to_string.
                ACE_DEBUG ((LM_DEBUG,
                            "opening a connection to the NamingService\n"
                            "resolving the CosName %s\n",
                            get_opt.opt_arg ()));

                CORBA::Object_var server_object;

                try
                  {
                    // Find the Naming Service.
                    CORBA::Object_var naming_context_object =
                      orb_var->resolve_initial_references ("NameService");
                    CosNaming::NamingContextExt_var naming_context =
                      CosNaming::NamingContextExt::_narrow (naming_context_object.in ());

                    if (CORBA::is_nil (naming_context.in ()))
                    {
                      ACE_ERROR_RETURN ((LM_ERROR,
                                        "NameService cannot be resolved\n"),
                                      -1);
                    }

                    CosNaming::Name *name =
                      naming_context->to_name (ACE_TEXT_ALWAYS_CHAR (get_opt.opt_arg ()));

                    try
                      {
                        server_object = naming_context->resolve (*name);
                          if (CORBA::is_nil (server_object.in ()))
                          {
                            ACE_ERROR_RETURN ((LM_ERROR,
                                  "name is not resolved to a valid object\n"),
                                              -1);
                          }
                      }
                    catch (const CosNaming::NamingContext::NotFound& nf)
                      {
                        const ACE_TCHAR *reason;

                        switch (nf.why)
                          {
                            case CosNaming::NamingContext::missing_node:
                              reason = ACE_TEXT ("missing node");
                              break;
                            case CosNaming::NamingContext::not_context:
                              reason = ACE_TEXT ("not context");
                              break;
                            case CosNaming::NamingContext::not_object:
                              reason = ACE_TEXT ("not object");
                              break;
                            default:
                              reason = ACE_TEXT ("not known");
                              break;
                          }
                        ACE_ERROR_RETURN ((LM_ERROR,
                                  "%s cannot be resolved, exception reason = %s\n",
                                          get_opt.opt_arg (),
                                          reason),
                                        -1);
                      }
                    catch (const CosNaming::NamingContext::InvalidName&)
                      {
                        ACE_ERROR_RETURN ((LM_ERROR,
                                      "%s cannot be resolved, exception reason = "
                                          "Invalid Name"
                                          "\n",
                                          get_opt.opt_arg ()),
                                        -1);
                      }
                    catch (const CosNaming::NamingContext::CannotProceed&)
                      {
                        ACE_ERROR_RETURN ((LM_ERROR,
                                      "%s cannot be resolved, exception reason = "
                                          "Cannot Proceed"
                                          "\n",
                                          get_opt.opt_arg ()),
                                        -1);
                      }
                    catch (const CORBA::Exception&)
                      {
                        ACE_ERROR_RETURN ((LM_ERROR,
                                      "%s cannot be resolved, exception reason = "
                                          "Unexpected Exception"
                                          "\n",
                                          argvw[0]),
                                          -1);
                      }

                    ACE_CString aString;

                    aString = orb_var->object_to_string (server_object.in ());

                    ACE_DEBUG ((LM_DEBUG,
                                "\nhere is the IOR\n%C\n\n",
                                aString.rep ()));

                    ACE_CString str;
                    b = catior_impl.decode(aString, str);
                    ACE_DEBUG ((LM_DEBUG, "%s", str.c_str()));
                  }
                catch (const CORBA::Exception&)
                  {
                    ACE_ERROR_RETURN ((LM_ERROR,
                                      "%s cannot be resolved, exception reason = "
                                      "Unexpected Exception"
                                      "\n",
                                      argvw[0]),
                                      -1);
                  }

                if (b == 1)
                  ACE_DEBUG ((LM_DEBUG,
                              "catior returned true\n"));
                else
                  ACE_DEBUG ((LM_DEBUG,
                              "catior returned false\n"));
                break;
              }
            case 'f':
              {
                int have_some_input = 0;
                int decode_pass_count = 0;

                //  Read the file into a CORBA::String_var.
                ACE_DEBUG ((LM_DEBUG,
                            "reading the file %s\n",
                            get_opt.opt_arg ()));

#if !defined (ACE_LACKS_IOSTREAM_TOTALLY)
                ifstream ifstr (ACE_TEXT_ALWAYS_CHAR(get_opt.opt_arg ()));

                if (!ifstr.good ())
                  {
                    ifstr.close ();
                    ACE_ERROR_RETURN ((LM_ERROR,
                                      "%s "
                                      "-f %s "
                                      "\n"
                                      "Invalid IOR file nominated"
                                      "\n",
                                      argvw[0],
                                      get_opt.opt_arg ()),
                                      -1);
                  }

                while (!ifstr.eof())
                  {
                    ACE_CString aString;

                    have_some_input = 0;

                    while (!ifstr.eof ())
                      {
                        char ch = 0;
                        ifstr.get (ch);
                        if (ifstr.eof () || ch == '\n' || ch == '\r')
                          break;
                        aString += ch;
                        ++have_some_input;
                      }
#else
                FILE* ifstr = ACE_OS::fopen (get_opt.opt_arg (), ACE_TEXT ("r"));

                if (!ifstr || ferror (ifstr))
                  {
                    if (ifstr)
                      {
                      ACE_OS::fclose (ifstr);
                      }
                      ACE_ERROR_RETURN ((LM_ERROR,
                                        "%s "
                                        "-f %s "
                                        "\n"
                                        "Invalid IOR file nominated"
                                        "\n",
                                        argvw[0],
                                        get_opt.opt_arg ()),
                                        -1);
                  }

                while (!feof (ifstr))
                  {
                    char ch;
                    ACE_CString aString;

                    have_some_input = 0;

                    while (!feof (ifstr))
                      {
                        ch = ACE_OS::fgetc (ifstr);
                        if (ch == EOF || ch == '\n' || ch == '\r')
                          break;
                        aString += ch;
                        ++have_some_input;
                      }
#endif /* !defined (ACE_LACKS_IOSTREAM_TOTALLY) */
                    if (have_some_input == 0 || !aString.length())
                      {
                        if (!decode_pass_count)
                          {
                              ACE_ERROR_RETURN ((LM_ERROR,
                                                "%s "
                                                "-f %s "
                                                "\n"
                                                "Empty IOR file nominated"
                                                "\n",
                                                argvw[0],
                                                get_opt.opt_arg ()),
                                                -1);
                          }
                        else
                          {
                            ACE_DEBUG ((LM_DEBUG,
                                        "catior returned true\n"));
                            return 0;               // All done now
                          }
                      }

                    ++decode_pass_count;

                    ACE_DEBUG ((LM_DEBUG,
                                "\nhere is the IOR\n%C\n\n",
                                aString.rep ()));

                    ACE_CString str;
                    b = catior_impl.decode(aString, str);
                    ACE_DEBUG ((LM_DEBUG, "%s", str.c_str()));
                  }
                if (b == 1)
                  ACE_DEBUG ((LM_DEBUG,
                              "catior returned true\n"));
                else
                  ACE_DEBUG ((LM_DEBUG,
                              "catior returned false\n"));
#if !defined (ACE_LACKS_IOSTREAM_TOTALLY)
                ifstr.close ();
#else
                ACE_OS::fclose (ifstr);
#endif /* !defined (ACE_LACKS_IOSTREAM_TOTALLY) */
              }
              break;
            case 'x':
              {
                int have_some_input = 0;
                int decode_pass_count = 0;

                //  Read the input into a CORBA::String_var.
                ACE_DEBUG ((LM_DEBUG,
                            "reading from stdin\n"));

    #if !defined (ACE_LACKS_IOSTREAM_TOTALLY)
                if (!cin.good ())
                  {
                    ACE_ERROR_RETURN ((LM_ERROR,
                                      "%s "
                                      "-x"
                                      "\n"
                                      "Invalid input stream"
                                      "\n",
                                      argvw[0]),
                                      -1);
                  }

                while (!cin.eof())
                  {
                    ACE_CString aString;

                    have_some_input = 0;

                    while (!cin.eof ())
                      {
                        char ch = 0;
                        cin.get (ch);
                        if (cin.eof () || ch == '\n' || ch == '\r')
                          break;
                        aString += ch;
                        ++have_some_input;
                      }
#else
                FILE* ifstr = stdin;

                if (!ifstr || ferror (ifstr))
                  {
                    if (ifstr)
                      {
                      ACE_OS::fclose (ifstr);
                      }
                    ACE_ERROR_RETURN ((LM_ERROR,
                                      "%s "
                                      "-x"
                                      "\n"
                                      "Invalid input stream"
                                      "\n",
                                      argvw[0]),
                                      -1);
                  }

                while (!feof (ifstr))
                  {
                    char ch;
                    ACE_CString aString;

                    have_some_input = 0;

                    while (!feof (ifstr))
                      {
                        ch = ACE_OS::fgetc (ifstr);
                        if (ch == EOF || ch == '\n' || ch == '\r')
                          break;
                        aString += ch;
                        ++have_some_input;
                      }
#endif /* !defined (ACE_LACKS_IOSTREAM_TOTALLY) */

                    if (have_some_input == 0)
                      {
                        if (!decode_pass_count)
                          {
                            ACE_ERROR_RETURN ((LM_ERROR,
                                              "%s "
                                              "-x"
                                              "\n"
                                              "Empty input stream"
                                              "\n",
                                              argvw[0]),
                                              -1);
                          }
                        else
                          {
                            return 0;               // All done now
                          }
                      }

                    ++decode_pass_count;

                    ACE_DEBUG ((LM_DEBUG,
                                "\nhere is the IOR\n%C\n\n",
                                aString.rep ()));

                    ACE_CString str;
                    b = catior_impl.decode(aString, str);
                    ACE_DEBUG ((LM_DEBUG, "%s", str.c_str()));
                  }
                if (b == 1)
                  ACE_DEBUG ((LM_DEBUG,
                              "catior returned true\n"));
                else
                  ACE_DEBUG ((LM_DEBUG,
                              "catior returned false\n"));
              }
              break;
            case '?':
            case 'h':
            default:
              ACE_ERROR_RETURN ((LM_ERROR,
                                "Usage: %s "
                                "-f filename "
                                "-n CosName "
                                "\n"
                                "Reads an IOR "
                                "and dumps the contents to stdout "
                                "\n",
                                argvw[0]),
                                1);
            }
        }

        // check that some relevant arguments have been supplied
        if (have_argument == 0)
              ACE_ERROR_RETURN ((LM_ERROR,
                                "Usage: %s "
                                "-f filename "
                                "-n CosName "
                                "\n"
                                "Reads an IOR "
                                "and dumps the contents to stdout "
                                "\n",
                                argvw[0]),
                                1);
    }
  catch (const CORBA::Exception& ex)
    {
      ACE_DEBUG ((LM_DEBUG, "\nError:\n"));
      ex._tao_print_exception ("Exception in nsadd");
      orb_var->destroy ();
      return 1;
    }
  return 0;
}
Esempio n. 15
0
int proc_lochange(const wstrings_c & pars)
{
    if (pars.size() < 3) return 0;
    wstr_c pts = pars.get(1); fix_path(pts, FNO_SIMPLIFY);

    if (!dir_present(pts))
    {
        Print(FOREGROUND_RED, "path-to-source not found: %s", pts.cstr()); return 0;
    }

    wstr_c ptl = pars.get(2); fix_path(ptl, FNO_SIMPLIFY);
    if (!dir_present(ptl))
    {
        Print(FOREGROUND_RED, "path-to-loc not found: %s", ptl.cstr()); return 0;
    }

    wstr_c tolocale = CONSTWSTR("en");
    if (pars.size() >= 4)
        tolocale = pars.get(3);

    wstrings_c lines;
    wstrings_c sfiles;
    fill_dirs_and_files(pts, sfiles, lines);


    hashmap_t<int, wstr_c> localehash;
    wstrings_c localelines;
    parse_text_file(fn_join(ptl, tolocale) + CONSTWSTR(".labels.lng"), localelines, true);
    for (const wstr_c &ls : localelines)
    {
        token<wchar> t(ls, '=');
        pwstr_c stag = *t;
        int tag = t->as_int(-1);
        ++t;
        wstr_c l(*t); l.trim();

        if (tag > 0)
            localehash[tag] = l;
    }


    for (const wstr_c & f : sfiles)
    {
        if (f.ends(CONSTWSTR(".h")) || f.ends(CONSTWSTR(".cpp")))
        {
            parse_text_file(f, lines);
            bool cmnt = false;
            bool changed = false;
            int cnt = lines.size();
            for (int ln = 0; ln < cnt; ++ln)
            {
                wstr_c & l = lines.get(ln);
                int workindex = 0;
                wstr_c txt;
                int tag, left, rite;

                while (findTTT(l, txt, tag, cmnt, left, rite, workindex))
                {
                    if (tag >= 0)
                    {
                        wstr_c txtto = localehash[tag];
                        l.replace( left, rite-left, CONSTWSTR("TTT(\"") + txtto + CONSTWSTR("\",") + wmake(tag) + CONSTWSTR(")") );
                        changed = true;
                    }
                }

            }
            if (changed)
                savelines(f, lines);

        }
    }
    return 0;
}
Esempio n. 16
0
int proc_loc(const wstrings_c & pars)
{
    if (pars.size() < 3) return 0;
    wstr_c pts = pars.get(1); fix_path(pts, FNO_SIMPLIFY);

    if (!dir_present(pts))
    { Print(FOREGROUND_RED, "path-to-source not found: %s", pts.cstr()); return 0; }

    wstr_c ptl = pars.get(2); fix_path(ptl, FNO_SIMPLIFY);
    if (!dir_present(ptl))
    { Print(FOREGROUND_RED, "path-to-loc not found: %s", ptl.cstr()); return 0; }

    wstrings_c lines;
    wstrings_c sfiles;
    fill_dirs_and_files(pts,sfiles,lines);

    tbuf_t<int> used_tags;

    struct rpl_s
    {
        wstr_c fn;
        wstr_c txt;
        int ln;
        int left;
        int rite;
        int tag;

        int operator()(const rpl_s&o) const
        {
            return SIGN( tag - o.tag );
        }
    };

    array_inplace_t<rpl_s, 128> need2rpl;

    for( const wstr_c & f : sfiles )
    {
        rpl_s r;
        r.fn = f;
        if (f.ends(CONSTWSTR(".h")) || f.ends(CONSTWSTR(".cpp")))
        {
            //tmp_str_c afn(f);
            //CHARz_copy(fnnnn, afn.cstr());

            parse_text_file(f,lines);
            bool cmnt = false;
            int cnt = lines.size();
            for(r.ln=0;r.ln<cnt;++r.ln)
            {
                const wstr_c & l = lines.get(r.ln);
                int workindex = 0;
                while (findTTT(l, r.txt, r.tag, cmnt, r.left, r.rite, workindex))
                {
                    //Print( FOREGROUND_GREEN, "TTT(%i): %s\n", r.tag, tmp_str_c(r.txt).cstr());
                    if (r.tag >= 0)
                    {
                        int i = used_tags.set(r.tag);
                        if (i < (used_tags.count()-1))
                        {
                            for(const rpl_s &rr : need2rpl)
                            {
                                if (rr.tag == r.tag)
                                {
                                    Print( FOREGROUND_RED, "%s(%i): Tag already used: TTT(%i): %s\n", to_str(rr.fn).cstr(), rr.ln, rr.tag, to_str(rr.txt).cstr());
                                }
                            }

                            Print( FOREGROUND_RED, "%s(%i): Tag already used: TTT(%i): %s\n", to_str(f).cstr(), r.ln, r.tag, to_str(r.txt).cstr());
                        }
                    }
                    need2rpl.add(r);
                }
                
            }
        }
    }


    //b.load_from_disk_file(str_c(fn_join(ptl, CONSTWSTR("en.labels.lng"))).as_sptr());
    //b.detect();
    //lngbp.load(b.as_str<wchar>());

    used_tags.sort();

    auto getfreetag = [&]()->int {
        static int lastchecktag = 0;
        tbuf_t<int>::default_comparator dc;
        for(aint tmp = 0;used_tags.find_index_sorted(tmp,++lastchecktag, dc););
        return lastchecktag;
    };

    wstr_c prevfile;
    bool lneschanged = false;
    for (rpl_s & r : need2rpl)
    {
        if (r.tag <= 0)
        {
            r.tag = getfreetag();

            if (prevfile != r.fn)
            {
                if (lneschanged)
                    savelines(prevfile, lines);
                lneschanged = false;
                parse_text_file(r.fn, lines);
                prevfile = r.fn;
            }

            wstr_c & l = lines.get(r.ln);
            l.replace( r.left, r.rite-r.left, CONSTWSTR("TTT(\"") + r.txt + CONSTWSTR("\",") + wmake(r.tag) + CONSTWSTR(")") );
            lneschanged = true;
        }
    }

    if (lneschanged)
        savelines(prevfile, lines);

    need2rpl.sort();

    FILE *f = fopen(to_str(fn_join(ptl, CONSTWSTR("en.labels.lng"))), "wb");
    swstr_c buf;

    //uint16 signa = 0xFEFF;
    //fwrite(&signa,2,1,f);

    for (const rpl_s & r : need2rpl)
    {
        buf.set_as_int( r.tag ).append(CONSTWSTR("=")).append(r.txt).append(CONSTWSTR("\r\n"));
        ts::str_c utf8 = to_utf8(buf);
        fwrite(utf8.cstr(), 1, utf8.get_length(), f);
    }
    fclose(f);

    //getch();
    return 0;
}
Esempio n. 17
0
void *connection_handler(void *socket_desc) {

    FILE *file;

    int sock = *(int*) socket_desc;
    int read_size;
    char *message, client_message[8192];
    OggStream* stream = 0;
    StreamMap streams;

    // start opus 
    int error;
    OpusDecoder *dec;
    dec = opus_decoder_create(16000, 1, &error);
    if (error != OPUS_OK && dec == NULL) {
        puts("ERROR LOADING OPUS");
    }

    // start pocketsphinx 
    ps_decoder_t *ps = ps_start();

    /* // IF RUN VAD AT SERVER
    VadInst* handle = NULL;
    if (WebRtcVad_Create(&handle) < 0) puts("Error creating WebRtcVad_Create");
    if (WebRtcVad_Init(handle) < 0) puts("Error initializing WebRtcVad_Init");
    if (WebRtcVad_set_mode(handle, 3) < 0) puts("Error setting mode WebRtcVad_set_mode");
     */

    char * dtdepois;
    bool ended = true;
    while ((read_size = recv(sock, client_message, 8192, 0)) > 0) {

        char otherString[3];
        strncpy(otherString, client_message, 3);

        if (strcmp(otherString, "#JS") == 0) {
            puts("GRAM RECVD. SWITCH");

            string str1(client_message);


            char *dtgram = current_timestamp();
            std::string grampath = "/var/www/speechrtc/voiceserver/" + std::string(dtgram) + ".jsgf";
            ofstream file;
            file.open(grampath.c_str());
            file << str1;
            file.close();


            jsgf_rule_iter_t *itor;
            jsgf_t * gram = jsgf_parse_file(grampath.c_str(), NULL);
            jsgf_rule_t * rule;

            for (itor = jsgf_rule_iter(gram); itor; itor = jsgf_rule_iter_next(itor)) {
                rule = jsgf_rule_iter_rule(itor);
                if (jsgf_rule_public(rule))
                    break;
            }

            fsg_model_t * m = jsgf_build_fsg(gram, rule, ps_get_logmath(ps), 6.5);
            fsg_set_t* fsgset = ps_get_fsgset(ps);
            fsg_set_add(fsgset,  dtgram , m);
            fsg_set_select(fsgset , dtgram );
            ps_update_fsgset(ps);
            continue;
        }

        if (strcmp(otherString, "STA") == 0) {

            //   int _res = ps_start_utt(ps, "goforward");            
            dtdepois = current_timestamp();
            puts(dtdepois);
            file = fopen(dtdepois, "wb+");
            ended = false;
            continue;
        }

        if (strcmp(otherString, "END") == 0) {
            puts("END RECVD");
            fclose(file);

            FILE *_file = fopen(dtdepois, "rb");
            char const *hyp, *uttid;
            int32 score;
            int rv = ps_decode_raw(ps, _file, dtdepois, -1);
            if (rv < 0) puts("error ps_decode_raw");
            hyp = ps_get_hyp(ps, &score, &uttid);

            if (hyp == NULL) {
                puts("Error hyp()");
                write(sock, "ERR", strlen("ERR"));
            } else {
                printf("Recognized: %s\n", hyp);
                // envia final hypothesis             
                write(sock, hyp, strlen(hyp));
            }

            fclose(_file);
            ended = true;
            continue;
        }


        if (ended) {
            puts("rcv packet after end. ignoring");
            continue;
        }

        // decode ogg
        ogg_sync_state state;
        ogg_page page;
        int ret = ogg_sync_init(&state);
        char *buffer = ogg_sync_buffer(&state, 8192);
        memcpy(buffer, client_message, 8192);
        ret = ogg_sync_wrote(&state, 8192);

        // here we accumulate the decoded pcm
        int totalpcm = 0;

        while (ogg_sync_pageout(&state, &page) == 1) {


            int serial = ogg_page_serialno(&page);


            if (ogg_page_bos(&page)) {
                stream = new OggStream(serial);
                ret = ogg_stream_init(&stream->mState, serial);
                streams[serial] = stream;
            } else {
                stream = streams[serial];
            }
            ret = ogg_stream_pagein(&stream->mState, &page);
            ogg_packet packet;
            while (ret = ogg_stream_packetout(&stream->mState, &packet)) {
                if (ret == 0) {
                    // Need more data to be able to complete the packet
                    puts("Need more data to be able to complete the packet");
                    continue;
                } else if (ret == -1) {
                    puts("// We are out of sync and there is a gap in the data. We lost a page somewhere.");
                    continue;
                }

                // A packet is available, this is what we pass  to opus
                stream->mPacketCount++;
                //puts("OGG OK");
                long length_pack = packet.bytes;
                unsigned char * data_pack = packet.packet;

                // decode opus 
                int frame_size = 1920;
                int lenaudio = frame_size * 1 * sizeof (opus_int16);
                //opus_int16 audio[lenaudio];
                short *in, *pcmsamples;
                pcmsamples = (short*) malloc(frame_size * 1 * sizeof (short));
                int totalpcm = opus_decode(dec, data_pack, length_pack, pcmsamples, frame_size, 0);

                // treat for more errors
                if (OPUS_INTERNAL_ERROR == totalpcm) puts("OPUS_INTERNAL_ERROR");
                else if (OPUS_INVALID_PACKET == totalpcm) {
                    puts("OPUS_INVALID_PACKET");
                } else {

                    //puts("OPUS OK. Sending PS");
                    puts("written to file");
                    fwrite(pcmsamples, 2, totalpcm, file);

                    //ps_process_raw(ps, pcmsamples, totalpcm, false, false);
                    // envia partial hypothesis to node.js send to browser 
                    // write(sock , client_message , strlen(client_message));



                }
            }
        }

        memset(client_message, 0, 8192);

    }
    if (read_size == 0) {

        // EVERYTHING CLEANED AT READ ERROR
        puts("Client disconnected");
        fflush(stdout);
        // ps_free(ps);

    } else if (read_size == -1) {
        perror("recv failed");
    }

    puts("ending handler");
    //    ps_free(ps);
    return 0;
}
Esempio n. 18
0
void
VTKXMLExportModule :: doOutput(TimeStep *tStep)
{
    if ( !testTimeStepOutput(tStep) ) {
        return;
    }
#ifdef __VTK_MODULE
    vtkSmartPointer<vtkUnstructuredGrid> stream = vtkSmartPointer<vtkUnstructuredGrid>::New();
    vtkSmartPointer<vtkPoints> nodes = vtkSmartPointer<vtkPoints>::New();
    vtkSmartPointer<vtkIdList> elemNodeArray = vtkSmartPointer<vtkIdList>::New();
#else
    FILE *stream = this->giveOutputStream(tStep);
    struct tm *current;
    time_t now;
    time(&now);
    current = localtime(&now);
    fprintf(stream, "<!-- TimeStep %e Computed %d-%02d-%02d at %02d:%02d:%02d -->\n", tStep->giveIntrinsicTime(), current->tm_year+1900, current->tm_mon+1, current->tm_mday, current->tm_hour,  current->tm_min,  current->tm_sec);
    fprintf(stream, "<VTKFile type=\"UnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\">\n");
    fprintf(stream, "<UnstructuredGrid>\n");
#endif


    Domain *d  = emodel->giveDomain(1);
    Element *elem;
    FloatArray *coords;
    int nelem = d->giveNumberOfElements();

    this->giveSmoother(); // make sure smoother is created

    // output nodes Region By Region
    int nregions = this->smoother->giveNumberOfVirtualRegions();
    int regionDofMans, totalcells;
    IntArray mapG2L, mapL2G;

    /* loop over regions */
    for ( int ireg = 1; ireg <= nregions; ireg++ ) {
        if ( ( ireg > 0 ) && ( this->regionsToSkip.contains(ireg) ) ) {
            continue;
        }

        // assemble local->global and global->local region map
        // and get number of single cells to process
        // the composite cells exported individually
        this->initRegionNodeNumbering(mapG2L, mapL2G, regionDofMans, totalcells, d, ireg);

        /* start default piece containing all single cell elements
         * the elements with composite geometry are assumed to be exported in individual pieces
         * after the default one
         */
#ifndef __PARALLEL_MODE
        if ( regionDofMans && totalcells ) {
#else
        if ( 1 ) {
#endif

#ifdef __VTK_MODULE
            for ( int inode = 1; inode <= regionDofMans; inode++ ) {
                coords = d->giveNode(mapL2G.at(inode))->giveCoordinates();
                int dims = coords->giveSize();
                nodes->InsertNextPoint(coords->at(1), dims >= 2 ? coords->at(2) : 0.0, dims >= 3 ? coords->at(3) : 0.0);
            }
            stream->SetPoints(nodes);
#else
            fprintf(stream, "<Piece NumberOfPoints=\"%d\" NumberOfCells=\"%d\">\n", regionDofMans, totalcells);
            // export nodes in region as vtk vertices
            fprintf(stream, "<Points>\n <DataArray type=\"Float64\" NumberOfComponents=\"3\" format=\"ascii\"> ");
            for ( int inode = 1; inode <= regionDofMans; inode++ ) {
                coords = d->giveNode( mapL2G.at(inode) )->giveCoordinates();
                for ( int i = 1; i <= coords->giveSize(); i++ ) {
                    fprintf( stream, "%e ", coords->at(i) );
                }

                for ( int i = coords->giveSize() + 1; i <= 3; i++ ) {
                    fprintf(stream, "%e ", 0.0);
                }
            }
            fprintf(stream, "</DataArray>\n</Points>\n");
#endif


            // output all cells of the piece
            int nelemNodes;
            IntArray cellNodes;
#ifdef __VTK_MODULE
            stream->Allocate(nelem);
#else
            fprintf(stream, "<Cells>\n");
            // output the connectivity data
            fprintf(stream, " <DataArray type=\"Int32\" Name=\"connectivity\" format=\"ascii\"> ");
#endif
            for ( int ielem = 1; ielem <= nelem; ielem++ ) {
                elem = d->giveElement(ielem);
                if ( ( ireg > 0 ) && ( this->smoother->giveElementVirtualRegionNumber(ielem) != ireg ) ) {
                    continue;
                }

                if ( this->isElementComposite(elem) ) {
                    continue;                                  // composite cells exported individually
                }

                if ( !elem-> isActivated(tStep) ) {                  //skip inactivated elements
                    continue;
                }
                
#ifdef __PARALLEL_MODE
                if ( elem->giveParallelMode() != Element_local ) {
                    continue;
                }
#endif


                nelemNodes = elem->giveNumberOfNodes();
                this->giveElementCell(cellNodes, elem, 0);
#ifdef __VTK_MODULE
                elemNodeArray->Reset();
                elemNodeArray->SetNumberOfIds(nelemNodes);
#endif
                for ( int i = 1; i <= nelemNodes; i++ ) {
#ifdef __VTK_MODULE
                    elemNodeArray->SetId(i-1, mapG2L.at( cellNodes.at(i) ) - 1);
#else
                    fprintf(stream, "%d ", mapG2L.at( cellNodes.at(i) ) - 1);
#endif
                }
#ifdef __VTK_MODULE
                stream->InsertNextCell(this->giveCellType(elem), elemNodeArray);
#else
                fprintf(stream, " ");
#endif
            }

#ifndef __VTK_MODULE
            int vtkCellType;
            fprintf(stream, "</DataArray>\n");
            // output the offsets (index of individual element data in connectivity array)
            fprintf(stream, " <DataArray type=\"Int32\" Name=\"offsets\" format=\"ascii\"> ");
            int offset = 0;
            for ( int ielem = 1; ielem <= nelem; ielem++ ) {
                elem = d->giveElement(ielem);
                if ( ( ireg > 0 ) && ( this->smoother->giveElementVirtualRegionNumber(ielem) != ireg ) ) {
                    continue;
                }

#ifdef __PARALLEL_MODE
                if ( elem->giveParallelMode() != Element_local ) {
                    continue;
                }

#endif
                offset += elem->giveNumberOfNodes();
                fprintf(stream, "%d ", offset);
            }

            fprintf(stream, "</DataArray>\n");

            // output cell (element) types
            fprintf(stream, " <DataArray type=\"UInt8\" Name=\"types\" format=\"ascii\"> ");
            for ( int ielem = 1; ielem <= nelem; ielem++ ) {
                elem = d->giveElement(ielem);
                if ( ( ireg > 0 ) && ( this->smoother->giveElementVirtualRegionNumber(ielem) != ireg ) ) {
                    continue;
                }

                if ( this->isElementComposite(elem) ) {
                    continue;                                  // composite cells exported individually
                }

#ifdef __PARALLEL_MODE
                if ( elem->giveParallelMode() != Element_local ) {
                    continue;
                }

#endif
                vtkCellType = this->giveCellType(elem);
                fprintf(stream, "%d ", vtkCellType);
            }

            fprintf(stream, "</DataArray>\n");
            fprintf(stream, "</Cells>\n");
#endif

            // export primary and internal variables
#ifndef __VTK_MODULE
            this->exportPointDataHeader(stream, tStep);
#endif
            this->exportPrimaryVars(stream, mapG2L, mapL2G, regionDofMans, ireg, tStep);
            this->exportIntVars(stream, mapG2L, mapL2G, regionDofMans, ireg, tStep);
#ifndef __VTK_MODULE
            fprintf(stream, "</PointData>\n");
#endif

            //export cell data
            this->exportCellVars(stream, ireg, tStep);

#ifndef __VTK_MODULE
            // end of piece record
            fprintf(stream, "</Piece>\n");
#endif
        } // end of default piece for simple geometry elements

#if 1
        // loop over region elements with multi-cell geometry
        for ( int ielem = 1; ielem <= nelem; ielem++ ) {
            elem = d->giveElement(ielem);

            if ( this->regionsToSkip.contains( this->smoother->giveElementVirtualRegionNumber(ielem) ) ) {
                continue;
            }

 #ifdef __PARALLEL_MODE
            if ( elem->giveParallelMode() != Element_local ) {
                continue;
            }

 #endif

            if ( this->isElementComposite(elem) ) {
#ifndef __VTK_MODULE
                ///@todo Not sure how to deal with this.
                // multi cell (composite) elements should support vtkxmlexportmoduleinterface
                // and are exported as individual pieces (see VTKXMLExportModuleElementInterface)
                VTKXMLExportModuleElementInterface *interface =
                    ( VTKXMLExportModuleElementInterface * ) elem->giveInterface(VTKXMLExportModuleElementInterfaceType);
                if ( interface ) {
                    // passing this to access general piece related methods like exportPointDataHeader, etc.
                    interface->_export(stream, this, primaryVarsToExport, internalVarsToExport, tStep);
                }
#endif
            }
        } // end loop over multi-cell elements
#endif
    } // end loop over regions

    std::string fname = giveOutputFileName(tStep);

#ifdef __VTK_MODULE
#if 0
    // Doesn't as well as I would want it to, interface to VTK is to limited to control this.
    // * The PVTU-file is written by every process (seems to be impossible to avoid).
    // * Part files are renamed and time step and everything else is cut off => name collisions
    vtkSmartPointer<vtkXMLPUnstructuredGridWriter> writer = vtkSmartPointer<vtkXMLPUnstructuredGridWriter>::New();
    writer->SetTimeStep(tStep->giveNumber()-1);
    writer->SetNumberOfPieces( this->emodel->giveNumberOfProcesses() );
    writer->SetStartPiece( this->emodel->giveRank() );
    writer->SetEndPiece( this->emodel->giveRank() );
#else
    vtkSmartPointer<vtkXMLUnstructuredGridWriter> writer = vtkSmartPointer<vtkXMLUnstructuredGridWriter>::New();
#endif
    writer->SetFileName(fname.c_str());
    writer->SetInput(stream);
    // Optional - set the mode. The default is binary.
    //writer->SetDataModeToBinary();
    //writer->SetDataModeToAscii();
    writer->Write();
#else
    // finish unstructured grid data and vtk file
    fprintf(stream, "</UnstructuredGrid>\n</VTKFile>");
    fclose(stream);
#endif

    // Writing the *.pvd-file. Only time step information for now. It's named "timestep" but is actually the total time.
    // First we check to see that there are more than 1 time steps, otherwise it is redundant;
#ifdef __PARALLEL_MODE
    if ( emodel->isParallel() && emodel->giveRank() == 0 ) {
        ///@todo Should use probably use PVTU-files instead. It is starting to get messy.
        // For this to work, all processes must have an identical output file name.
        for (int i = 0; i < this->emodel->giveNumberOfProcesses(); ++i) {
            std::ostringstream pvdEntry;
            char fext[100];
            if (this->emodel->giveNumberOfProcesses() > 1) {
                sprintf( fext, "_%03d.m%d.%d", i, this->number, tStep->giveNumber() );
            } else {
                sprintf( fext, "m%d.%d", this->number, tStep->giveNumber() );
            }
            pvdEntry << "<DataSet timestep=\"" << tStep->giveIntrinsicTime() << "\" group=\"\" part=\"" << i << "\" file=\""
                    << this->emodel->giveOutputBaseFileName() << fext << ".vtu\"/>";
            this->pvdBuffer.push_back(pvdEntry.str());
        }
        this->writeVTKCollection();
    } else
#endif
    if ( !emodel->isParallel() && tStep->giveNumber() >= 1 ) { // For non-parallel enabled OOFEM, then we only check for multiple steps.
        std::ostringstream pvdEntry;
        pvdEntry << "<DataSet timestep=\"" << tStep->giveIntrinsicTime() << "\" group=\"\" part=\"\" file=\"" << fname << "\"/>";
        this->pvdBuffer.push_back(pvdEntry.str());
        this->writeVTKCollection();
    }
}

#ifndef __VTK_MODULE
void
VTKXMLExportModule :: exportPointDataHeader(FILE *stream, TimeStep *tStep)
{
    int n;
    std :: string scalars, vectors, tensors;

    n = primaryVarsToExport.giveSize();

    UnknownType type;

    for ( int i = 1; i <= n; i++ ) {
        type = ( UnknownType ) primaryVarsToExport.at(i);
        if ( ( type == DisplacementVector ) || ( type == EigenVector ) || ( type == VelocityVector ) ) {
            vectors += __UnknownTypeToString(type);
            vectors.append(" ");
        } else if ( ( type == FluxVector ) || ( type == PressureVector ) || ( type == Temperature ) ) {
            scalars += __UnknownTypeToString(type);
            scalars.append(" ");
        } else {
            OOFEM_ERROR2( "VTKXMLExportModule::exportPrimVarAs: unsupported UnknownType %s", __UnknownTypeToString(type) );
        }
    }

    InternalStateType isttype;
    InternalStateValueType vtype;


    n = internalVarsToExport.giveSize();

    // prepare header
    for ( int i = 1; i <= n; i++ ) {
        isttype = ( InternalStateType ) internalVarsToExport.at(i);
        vtype = giveInternalStateValueType(isttype);

        if ( vtype == ISVT_SCALAR ) {
            scalars += __InternalStateTypeToString(isttype);
            scalars.append(" ");
        } else if ( vtype == ISVT_VECTOR ) {
            vectors += __InternalStateTypeToString(isttype);
            vectors.append(" ");
        } else if ( ( vtype == ISVT_TENSOR_S3 ) || ( vtype == ISVT_TENSOR_S3E ) ) {
            tensors += __InternalStateTypeToString(isttype);
            tensors.append(" ");
        } else if ( vtype == ISVT_TENSOR_G ) {
            vectors += __InternalStateTypeToString(isttype);
            vectors.append(" ");
        } else {
            fprintf( stderr, "VTKXMLExportModule::exportIntVars: unsupported variable type %s\n", __InternalStateTypeToString(isttype) );
        }
    }

    // print header
    fprintf( stream, "<PointData Scalars=\"%s\" Vectors=\"%s\" Tensors=\"%s\" >\n",
            scalars.c_str(), vectors.c_str(), tensors.c_str() );
}
Esempio n. 19
0
int main (int argc, char *argv[])
{
    const int n = (1 < argc) ? atoi(argv[1]) : 1000000;  // number of
                                                           // iterations

#if defined( STDIO )
    FILE * target;
    target = stdout;
    if (2 < argc) {  // place output in file
        target = fopen( argv[2], "w" );
    }
#else                                         // for both iostreams libs
    ofstream target;
    ostream* op = &cout;
    if (2 < argc) {  // place output in file
        target.open(argv[2]);
        op = &target;
    }
    ostream& out = *op;
#endif

    int i;                              // for-loop variable

                                        // output command for documentation:
#if defined( STDIO )
    for (i = 0; i < argc; ++i)
        fprintf( target, "%s ", argv[i]) ;
    fprintf( target, "\n" );
#else
    for (i = 0; i < argc; ++i)
        out << argv[i] << " ";
    out << "\n";
#endif

    std::vector<T> v;                        // holds elapsed time of the tests

#if !defined( STDIO)
    #if defined (CLASSIC)
    // non-synchronized I/O is the default
    #else
    out.sync_with_stdio (false);       // must be called before any output
    #endif
#endif

    // seed the random number generator
    srand( clock() );
    clock_t t = clock();
    if (t == clock_t(-1))
    {
#if defined( STDIO )
        fprintf( stderr, "sorry, no clock\n" );
#else
        cerr << "sorry, no clock\n";
#endif
        exit(1);
    }


#if defined( STDIO )
    t = clock();
    for (i = 0; i != n; ++i)
    {
       fprintf ( target, "%d ", i);
    }
    v.push_back(T("output integers to stdio                      ", clock() - t));

    t = clock();
    for ( i = 0; i != n; ++i)
    {
       fprintf ( target, "%x ", i);
    }
    v.push_back(T("output hex integers to stdio                  ", clock() - t));

    if (clock() == clock_t(-1))
    {
        fprintf ( stderr, "sorry, clock overflow\n" );
        exit(2);
    }

    // output results
    fprintf ( stderr, "\n" );
    for (i = 0; static_cast<size_t>(i)<v.size(); i++)
        fprintf( stderr, "%s :\t%f seconds\n", v[i].s, v[i].t /CLOCKS_PER_SEC );

#else
    t = clock();
    for ( i = 0; i != n; ++i)
    {
            out << i << ' ';
    }
    v.push_back(T("output integers (sync = false)       ", clock() - t));

    out << hex;
    t = clock();
    for ( i = 0; i != n; ++i)
    {
            out << i << ' ';
    }
    v.push_back(T("output hex integers (sync = false)   ", clock() - t));

    #if defined (CLASSIC)
    out.sync_with_stdio();             // synchronize -- no argument needed
    #else
    out.sync_with_stdio (true);
    #endif

    out << dec;
    t = clock();
    for ( i = 0; i != n; ++i)
    {
            out << i << ' ';
    }
    v.push_back(T("output integers (sync = true)        ", clock() - t));

    out << hex;
    t = clock();
    for ( i = 0; i != n; ++i)
    {
            out << i << ' ';
    }
    v.push_back(T("output hex integers (sync = true)     ", clock() - t));

    if (clock() == clock_t(-1))
    {
        cerr << "sorry, clock overflow\n";
        exit(2);
    }

    // output results
    cerr << endl;
    for (i = 0; static_cast<size_t>(i) < v.size(); i++)
        cerr << v[i].s << " :\t"
            << v[i].t /CLOCKS_PER_SEC
            << " seconds" << endl;
#endif

    return 0;

}
Esempio n. 20
0
int read(int fid, void *buf, unsigned int nbytes)
{
  int hchar = 0, read = 0;
  FILE *file;

  /*-------------------------------------------------------------------*/
  /* If number of requested bytes is zero, return zero.                */
  /*-------------------------------------------------------------------*/
  if (nbytes == 0)
    return 0;

#if OS_PARM_CHECK
  /*-------------------------------------------------------------------*/
  /* Ensure file descriptor is valid.                                  */
  /*-------------------------------------------------------------------*/
  if (fid < 0 || fid >= FOPEN_MAX)
  {
    set_errno(EBADF);
    return -1;
  }

  /*-------------------------------------------------------------------*/
  /* Return error if buffer pointer is invalid.                        */
  /*-------------------------------------------------------------------*/
  if (buf == NULL)
  {
    Files[fid].errcode = EFAULT;
    set_errno(EFAULT);
    return -1;
  }
#endif

  /*-------------------------------------------------------------------*/
  /* Acquire exclusive read access to file.                            */
  /*-------------------------------------------------------------------*/
  file = &Files[fid];
  file->acquire(file, F_READ);

  /*-------------------------------------------------------------------*/
  /* Return error if file is closed.                                   */
  /*-------------------------------------------------------------------*/
  if (file->ioctl == NULL)
  {
    set_errno(EBADF);
    file->release(file, F_READ);
    return -1;
  }

  /*-------------------------------------------------------------------*/
  /* If available, read pushed-back character first.                   */
  /*-------------------------------------------------------------------*/
  if (file->hold_char)
  {
    ui8 *cp = buf;

    *cp = (ui8)file->hold_char;
    buf = cp + 1;
    file->hold_char = 0;
    hchar = 1;
    --nbytes;
  }

  /*-------------------------------------------------------------------*/
  /* Check if there are more characters to read.                       */
  /*-------------------------------------------------------------------*/
  if (nbytes)
  {
    /*-----------------------------------------------------------------*/
    /* Pass read request to file system or device driver.              */
    /*-----------------------------------------------------------------*/
    read = file->read(file, buf, nbytes);

    /*-----------------------------------------------------------------*/
    /* Read error is disregarded iff pushed-back character was read.   */
    /*-----------------------------------------------------------------*/
    if (read == -1)
    {
      if (hchar)
        read = 0;
      else
        file->errcode = get_errno();
    }
  }

  /*-------------------------------------------------------------------*/
  /* Release exclusive read access to file.                            */
  /*-------------------------------------------------------------------*/
  file->release(file, F_READ);

  /*-------------------------------------------------------------------*/
  /* Return number of bytes successfully read or -1.                   */
  /*-------------------------------------------------------------------*/
  return read + hchar;
}