コード例 #1
0
ファイル: melder_ftoa.cpp プロジェクト: READSEARCH/praat
const char * Melder8_integer (int64 value) {
	if (++ ibuffer == NUMBER_OF_BUFFERS) ibuffer = 0;
	if (sizeof (long) == 8) {
		int n = snprintf (buffers8 [ibuffer], MAXIMUM_NUMERIC_STRING_LENGTH + 1, "%ld", (long) value);   // cast to identical type, to make compiler happy
		Melder_assert (n > 0);
		Melder_assert (n <= MAXIMUM_NUMERIC_STRING_LENGTH);
	} else if (sizeof (long long) == 8) {
		/*
		 * There are buggy platforms (namely 32-bit Mingw on Windows XP) that support long long and %lld but that convert
		 * the argument to a 32-bit long.
		 * There are also buggy platforms (namely 32-bit gcc on Linux) that support long long and %I64d but that convert
		 * the argument to a 32-bit long.
		 */
		static const char *formatString = nullptr;
		if (! formatString) {
			char tryBuffer [MAXIMUM_NUMERIC_STRING_LENGTH + 1];
			formatString = "%lld";
			sprintf (tryBuffer, formatString, 1000000000000LL);
			if (! strequ (tryBuffer, "1000000000000")) {
				formatString = "%I64d";
				sprintf (tryBuffer, formatString, 1000000000000LL);
				if (! strequ (tryBuffer, "1000000000000")) {
					Melder_fatal (U"Found no way to print 64-bit integers on this machine.");
				}
			}
		}
		int n = snprintf (buffers8 [ibuffer], MAXIMUM_NUMERIC_STRING_LENGTH + 1, formatString, value);
		Melder_assert (n > 0);
		Melder_assert (n <= MAXIMUM_NUMERIC_STRING_LENGTH);
	} else {
		Melder_fatal (U"Neither long nor long long is 8 bytes on this machine.");
	}
	return buffers8 [ibuffer];
}
コード例 #2
0
ファイル: main.cpp プロジェクト: nemequ/tornado
// Callback function called by compression routine to read/write data.
static int ReadWriteCallback (const char *what, void *buf, int size, void *_r)
{
  Results &r = *(Results*)_r;        // Accumulator for compression statistics

  if (strequ(what,"read")) {
    int n = file_read (r.fin, buf, size);
    r.insize += n;
    return n;

  } else if (strequ(what,"write")) {
    if (r.fout)
      if (size != file_write (r.fout, buf, size))
        return FREEARC_ERRCODE_WRITE;
    r.outsize += size;
    return size;

  } else if (strequ(what,"progress")) {
    r.progress_insize  += ((int64*)buf)[0];
    r.progress_outsize += ((int64*)buf)[1];
    print_stats(r);
    return FREEARC_OK;

  } else {
    return FREEARC_ERRCODE_NOT_IMPLEMENTED;
  }
}
コード例 #3
0
ファイル: dsc.c プロジェクト: OS2World/UTIL-CONV-a2ps
/*
 * Dump the needed resources _BUT_ the colors
 */
void
dump_needed_resources (FILE * stream, a2ps_job * job)
{
  int i;
  int first = 1;

  multivalued_entry ** list;
  list = ((multivalued_entry **)
	  hash_dump (job->status->needed_resources, NULL, NULL));

  for (i = 0 ; list [i] ; i ++)
    {
      /* Don't print the colors, because they have another section */
      if (strequ (list [i]-> key, "color")
	  /* nor files, since they are yet included */
	  || strequ (list [i]-> key, "file"))
	continue;

      multivalued_entry_dump (stream, first,
			      "%%%%DocumentNeededResources: %s %s\n",
			      "%%%%+ %s %s\n",
			      list [i]);
      first = false;
    }

  free (list);
}
コード例 #4
0
ファイル: machine.cpp プロジェクト: pineking/praat
void Machine_initLookAndFeel (unsigned int argc, char **argv) {
	/*
	 * Determining the appropriate look-and-feel: the default depends on the client machine.
	 */
	#if defined (macintosh)
		lookAndFeel = LookAndFeel_COCOA;
		return;
	#elif defined (_WIN32)
		lookAndFeel = LookAndFeel_WIN32;
		return;
	#elif defined (linux)
		lookAndFeel = LookAndFeel_LINUX;
	#endif

	/*
	 * Command line may override the look-and-feel.
	 */
	if (argc > 1) {
		if (strequ (argv [1], "-sgi")) lookAndFeel = LookAndFeel_SGI;
		else if (strequ (argv [1], "-motif")) lookAndFeel = LookAndFeel_MOTIF;
		else if (strequ (argv [1], "-cde")) lookAndFeel = LookAndFeel_CDE;
		else if (strequ (argv [1], "-solaris")) lookAndFeel = LookAndFeel_SOLARIS;
		else if (strequ (argv [1], "-hp")) lookAndFeel = LookAndFeel_HP;
		else if (strequ (argv [1], "-sun4")) lookAndFeel = LookAndFeel_SUN4;
		else if (strequ (argv [1], "-mac")) lookAndFeel = LookAndFeel_MAC;
		else if (strequ (argv [1], "-linux")) lookAndFeel = LookAndFeel_LINUX;
		else if (strequ (argv [1], "-cocoa")) lookAndFeel = LookAndFeel_COCOA;
	}
}
コード例 #5
0
ファイル: ungbfs.c プロジェクト: maestun/ishargba
int main(int argc, char **argv)
{
  FILE *fp;
  char filename[32] = {0};
  u32 dir_off, dir_nmemb;
  unsigned int i;

  if(argc != 2 || strequ("-h", argv[1]) || strequ("--help", argv[1]))
  {
    fputs("dumps the objects in a gbfs file to separate files\n"
          "syntax: ungbfs FILE\n", stderr);
    return 1;
  }

  fp = fopen(argv[1], "rb");
  if(!fp)
  {
    fputs("could not open ", stderr);
    perror(argv[1]);
    return 1;
  }

  /* read pertinent header fields */
  fseek(fp, 20, SEEK_SET);
  dir_off = fgeti16(fp);
  dir_nmemb = fgeti16(fp);

  for(i = 0; i < dir_nmemb; i++)
  {
    unsigned long len, off;
    FILE *outfile;

    fseek(fp, dir_off + 32 * i, SEEK_SET);
    fread(filename, 24, 1, fp);
    len = fgeti32(fp);
    off = fgeti32(fp);
    printf("%10lu %s\n", (unsigned long)len, filename);

    outfile = fopen(filename, "wb");
    if(!outfile)
    {
      fputs("could not open ", stderr);
      perror(filename);
      fclose(fp);
      return 1;
    }
    fseek(fp, off, SEEK_SET);
    fncpy(outfile, fp, len);
    fclose(outfile);
  }

  fclose(fp);
  return 0;
}
コード例 #6
0
ファイル: main.cpp プロジェクト: nemequ/tornado
// Print current compression statistics
static void print_stats (Results &r)
{
#ifndef FREEARC_NO_TIMING
  FILESIZE insize  = r.progress_insize;   bool not_enough_input   =  (insize  - r.last_insize  < PROGRESS_CHUNK_SIZE);
  FILESIZE outsize = r.progress_outsize;  bool not_enough_output  =  (outsize - r.last_outsize < PROGRESS_CHUNK_SIZE);
  if (r.quiet_progress  ||  insize==0  ||  outsize==0  ||  not_enough_input && not_enough_output)  return;   // Prints stats no more often than once per 64 kb
  r.last_insize  = insize;
  r.last_outsize = outsize;
  double curtime = GetSomeTime();

  // Update progress indicator every 0.2 seconds
  if (curtime > r.lasttime+0.2)
  {
    double time = curtime - r.start_time;      // Time used so far
    char percents0[100] = "",  remains0[100] = "", percents[1000] = "",  remains[100] = "",  insize_str[100],  outsize_str[100];
    if (r.filesize)
    {
      // If progress by 1% takes more than 1-2 seconds - display xx.x%, otherwise xx%
      // (we don't want to switch it too frequently, therefore "?1:2")
      r.show_exact_percent  =  double(r.filesize)/insize*time > (r.show_exact_percent?1:2)*100;
      if (r.show_exact_percent)
           sprintf (percents0, "%.1lf%%", double(int(double(insize)*100/r.filesize*10))/10);
      else sprintf (percents0, "%d%%", int(double(insize)*100/r.filesize));
      sprintf (percents, "%s: ", percents0);

      int remain = int(double(r.filesize-insize)/insize*time)+1;
      if (remain>=3600)
           sprintf (remains0, "%02d:%02d:%02d", remain / 3600, (remain % 3600) / 60, remain % 60);
      else sprintf (remains0, "%02d:%02d", remain / 60, remain % 60);
      sprintf (remains, ". Remains %s", remains0);
    }
    double origsize  = (r.mode==_COMPRESS? insize  : outsize);         // Size of original (uncompressed) data
    double compsize  = (r.mode==_COMPRESS? outsize : insize);          // Size of compressed data
    double ratio     = (compsize/origsize)*100;
    double speed     = (origsize/mb) / mymax(time,0.001);              // Speed of processing, in MiB/s
    if (!r.quiet_result && !strequ (r.outname, "-"))
      fprintf (stderr, "\r%s%s%s -> %s: %.2lf%%, speed %.3lf mb/sec%s   ",
               r.method_name, percents, show3(insize,insize_str), show3(outsize,outsize_str), ratio, speed, remains);

    if (!r.quiet_title  &&  r.filesize  &&  curtime > r.lasttime2+0.5)   // Update window title every 0.5 seconds
    {
      const char *op  =  (r.mode==_COMPRESS? "Compressing": r.mode==_DECOMPRESS? "Extracting": "Benchmarking");
      sprintf (percents, "%s %s | %s %s", percents0, remains0, op, strequ(r.filename,"-")? PROGRAM_NAME : r.filename);
      EnvSetConsoleTitleA (percents);
      Taskbar_SetProgressValue (insize, r.filesize);
      r.lasttime2 = curtime;
    }
    r.lasttime = curtime;
  }
#endif
}
コード例 #7
0
ファイル: tormem.cpp プロジェクト: farruggia/TurboBench
int ReadWriteMem (const char *what, void *buf, int size, void *_bufio)
{
  bufio *bufio = (struct bufio *)_bufio;
  if (strequ(what,"read")) {
    if(bufio->rdp + size > bufio->rde) size = bufio->rde - bufio->rdp;
    memcpy(buf, bufio->rdp, size);
    bufio->rdp += size;
    return size;
  } else if (strequ(what,"write")) {
    memcpy (bufio->wrp, buf, size);
    bufio->wrp  += size;
    return size;
  }
  return FREEARC_OK;
}
コード例 #8
0
 void TcpSymbianSerial::handleDisconnect(const char* method, uint32 src)
 {
    m_keepConnectionTimeout = 0;
    if(method && isdigit(*method)){
       uint32 timeoutTime = 0;
       char* endp = NULL;
       timeoutTime = strtoul(method, &endp, 10);
       if(endp != method){
          m_keepConnectionTimeout = timeoutTime;
       }
    }
    DBG("KeepConnectionTimeout parsed to %"PRIu32, m_keepConnectionTimeout);
    if(method && delayDisconnect() && !strequ(method, "FAKETIMEOUT")){
       DBG("Fake Disconnect!");
       sendConnectionNotify(DISCONNECTING, REQUESTED, src);
       sendConnectionNotify(CLEAR, UNSPECIFIED, src);
       m_queue->setTimer(m_connectionTimer, SYMBIAN_DELAY_AMOUNT);
    } else {
       DBG("Real disconnect");
       if(m_tcpAdmin){
          m_tcpAdmin->ConnectionControl(DISCONNECT, method);
       }
    }
    DBG("DISCONNECTION COMPLETE");
 }
コード例 #9
0
   Output* OutputFactory::createOutput(const char* target) 
   {
      Output* ret = NULL;
      if(target == NULL) target = "null";
      char* memref = new char[strlen(target) + 1];
      char* remaining = memref;
      strcpy(remaining, target);
      const char delim[] = ":";
      char* type = strsep(&remaining, delim);
      if(strequ(type, "file")){

#define TENK 102400
#ifdef _MSC_VER
# define NUMFILES 1
# define FILESIZE (100 * TENK)
#else
# define NUMFILES 4
# define FILESIZE (6 * TENK)
#endif
         ret = RFileOutput::New(remaining, false, false, NUMFILES, FILESIZE);
      }else if(strequ(type, "tcp")){
         uint16 thePort = 0;
         char* host = NULL;
         char* threadName = new char[strlen(remaining) + 1];
         strcpy(threadName, remaining);
         if(!isdigit(*remaining)){
            host = strsep(&remaining, delim);
         } 
         long port = strtol(remaining, NULL, 10);
         if(port > 1 && port <= MAX_UINT16){
            thePort = uint16(port & 0x0ffff);
         }
         if(host && thePort != 0){
            ret = new SocketOutput(threadName, host, thePort);
         } else if(thePort != 0){
            /* NOT POSSIBLE! */
/*             ret = new SocketOutput(threadName, thePort); */
         }
         delete[] threadName;
      }
      delete[] memref;
      return ret;
   }
コード例 #10
0
ファイル: Collection.cpp プロジェクト: DsRQuicke/praat
void _CollectionOfDaata_v_readText (_CollectionOfDaata* me, MelderReadText text, int formatVersion) {
	if (formatVersion < 0) {
		long l_size;
		autostring8 line = Melder_32to8 (MelderReadText_readLine (text));
		if (! line.peek() || ! sscanf (line.peek(), "%ld", & l_size) || l_size < 0)
			Melder_throw (U"Collection::readText: cannot read size.");
		my _grow (l_size);
		for (long i = 1; i <= l_size; i ++) {
			long itemNumberRead;
			int n = 0, length, stringsRead;
			char klas [200], nameTag [2000];
			do {
				line.reset (Melder_32to8 (MelderReadText_readLine (text)));
				if (! line.peek())
					Melder_throw (U"Missing object line.");
			} while (strncmp (line.peek(), "Object ", 7));
			stringsRead = sscanf (line.peek(), "Object %ld: class %s %s%n", & itemNumberRead, klas, nameTag, & n);
			if (stringsRead < 2)
				Melder_throw (U"Collection::readText: cannot read header of object ", i, U".");
			if (itemNumberRead != i)
				Melder_throw (U"Collection::readText: read item number ", itemNumberRead,
					U" while expecting ", i, U".");
			if (stringsRead == 3 && ! strequ (nameTag, "name"))
				Melder_throw (U"Collection::readText: wrong header at object ", i, U".");
			my at [i] = (Daata) Thing_newFromClassName (Melder_peek8to32 (klas), nullptr).releaseToAmbiguousOwner();
			my size ++;
			if (! Thing_isa (my at [i], classDaata) || ! Data_canReadText (my at [i]))
				Melder_throw (U"Cannot read item of class ", Thing_className (my at [i]), U" in collection.");
			Data_readText (my at [i], text, -1);
			if (stringsRead == 3) {
				if (line [n] == U' ') n ++;   // skip space character
				length = strlen (line.peek()+n);
				if (length > 0 && (line.peek()+n) [length - 1] == '\n')
					(line.peek()+n) [length - 1] = '\0';
				Thing_setName (my at [i], Melder_peek8to32 (line.peek()+n));
			}
		}
	} else {
		int32_t l_size = texgeti4 (text);
		my _grow (l_size);
		for (int32_t i = 1; i <= l_size; i ++) {
			autostring32 className = texgetw2 (text);
			int elementFormatVersion;
			my at [i] = (Daata) Thing_newFromClassName (className.peek(), & elementFormatVersion).releaseToAmbiguousOwner();
			my size ++;
			if (! Thing_isa (my at [i], classDaata) || ! Data_canReadText (my at [i]))
				Melder_throw (U"Cannot read item of class ", Thing_className (my at [i]), U" in collection.");
			autostring32 objectName = texgetw2 (text);
			Thing_setName (my at [i], objectName.peek());
			Data_readText (my at [i], text, elementFormatVersion);
		}
	}
}
コード例 #11
0
ファイル: tor_test.cpp プロジェクト: bobhansen/lzbench
// Callback function called by compression routine to read/write data.
// Also it's called by the driver to init/shutdown its processing
int ReadWriteCallback (const char *what, void *buf, int size, void *r_)
{
  Results &r = *(Results*)r_;        // Accumulator for compression statistics

//  printf("what=%s size=%d\n", what, size);

  if (strequ(what,"init")) {
  
	  r.inpos = r.outlen = 0;
	  return FREEARC_OK;

  } else if (strequ(what,"read")) {
    if (r.inpos + size > r.inlen)
		size = r.inlen - r.inpos;

	memcpy(buf, r.inbuf+r.inpos, size);
	r.inpos += size;
    return size;

  } else if (strequ(what,"write") || strequ(what,"quasiwrite")) {
    if (strequ(what,"write")) {
		memcpy(r.outbuf+r.outlen, buf, size);
		r.outlen += size;
		return size;
	}

  } else if (strequ(what,"done")) {
    // Print final compression statistics
    return FREEARC_OK;

  } else {
    return FREEARC_ERRCODE_NOT_IMPLEMENTED;
  }
}
コード例 #12
0
ファイル: scanners.c プロジェクト: tromey/idutils
struct language *
get_language (char const *lang_name)
{
    const struct language *lang;
    for (lang = languages_0; lang < languages_N; lang++)
        if (strequ (lang_name, lang->lg_name))
        {
            DEBUG (("lang=%s", lang_name));
            return (struct language *) lang;
        }
    DEBUG (("!lang=%s", lang_name));
    return 0;
}
コード例 #13
0
ファイル: printers.c プロジェクト: OS2World/UTIL-CONV-a2ps
/*
 * Record a printer defined by the config line "Printer:"
 */
bool
a2ps_printers_add (struct a2ps_printers_s * printers,
		   const char * key, char * definition)
{
  char * ppdkey = NULL;
  char * token = NULL;
  char * command = NULL;

  /* Skip the blanks */
  token = definition + strspn (definition, " \t");

  /* PPD given ? */
  if ((*token != '>') && (*token != '|'))
    {
      /* If the first token does not start by `|' or `>', then ppdkey
        is defined */
      ppdkey = strtok (token, " \t");
      token = strtok (NULL, "\n");
    }
  else
    {
      /* Skip the blanks. */
      token += strspn (token, " \t");
    }

  /* What remains is the command itself (can be NULL). */
  command = token;

  /* Special printers. */
  if (strequ (key, DEFAULT_PRINTER))
    printer_set (&printers->default_printer, ppdkey, command);
  else if (strequ (key, UNKNOWN_PRINTER))
    printer_set (&printers->unknown_printer, ppdkey, command);
  else
    printer_table_add (printers->printers, key, ppdkey, command);

  /* Success. */
  return true;
}
コード例 #14
0
ファイル: main.cpp プロジェクト: nemequ/tornado
// Print current compression statistics
static void start_print_stats (Results &r)
{
  r.insize = r.outsize = r.progress_insize = r.progress_outsize = r.last_insize = r.last_outsize = 0;
  r.show_exact_percent = FALSE;
  r.start_time = r.lasttime = r.lasttime2 = GetSomeTime();
#ifdef FREEARC_WIN
  if (strequ (r.filename, "-"))   // On windows, get_flen cannot return real filesize in situations like "type file|tor"
      r.filesize = -1;
  else
#endif
      r.filesize = get_flen(r.fin);
  sprintf(r.method_name, r.mode==_COMPRESS? "-%d: " : "", r.method.number);
}
コード例 #15
0
ファイル: main.cpp プロジェクト: doug16rogers/dr
// ---------------------------------------------------------------------------
void Load_Arguments (int& argc, char* argv[])
{
  for (int i = 1; i < argc; i++)
  {
    char* argument = argv[i];
    if ((strcmp (argument, "--help") == 0) || strequ(argument, "-h")) Usage();
    else if (strequ (argument, "-epoch=" )) Set_Epoch  (strchr (argument, '=') + 1);
    else if (strequ (argument, "-format=")) Set_Format (strchr (argument, '=') + 1);
    else if (strequ (argument, "-verbose")) verbose = 1;
    else
    {
      fprintf (stderr, PROGRAM_NAME ": *** error: unknown option \"%s\".\n\n", argument);
      Usage();
      return;
    }

    for (int j = i; (j+1) < argc; j++)
    {
      argv[j] = argv[j+1];
    }
    i--;
    argc--;
  }
}   // Load_Arguments
コード例 #16
0
ファイル: C_CLS.cpp プロジェクト: RamiroCruzo/freearc_src
// Конструирует объект типа CLS_METHOD с заданными параметрами упаковки
// или возвращает NULL, если это другой метод сжатия или допущена ошибка в параметрах
COMPRESSION_METHOD* parse_CLS (char** parameters, void *method_template)
{
  if (strequ (parameters[0], ((CLS_METHOD*)method_template)->name)) {
    // Если название метода (нулевой параметр) соответствует названию проверяемого CLS метода, то разберём остальные параметры
    CLS_METHOD *p = new CLS_METHOD (*(CLS_METHOD*)method_template);

    // Record method parameters if exists
    if (parameters[1])
        strcpy(p->params, parameters[1]);

    return p;
  } else {
    return NULL;   // Это не метод CLS
  }
}
コード例 #17
0
ファイル: printers.c プロジェクト: OS2World/UTIL-CONV-a2ps
/*
 * Accessing the output fields
 */
void
a2ps_printers_flag_output_set (struct a2ps_printers_s * printers,
			       const char * flag_output_name,
			       bool is_printer)
{
  printers->flag_output_is_printer = is_printer;

  if (!is_printer && flag_output_name && strequ (flag_output_name, "-"))
    {
      /* Request for stdin */
      XFREE (printers->flag_output_name);
      printers->flag_output_name = NULL;
    }
  else
    xstrcpy (printers->flag_output_name, flag_output_name);
}
コード例 #18
0
ファイル: x_snmp.c プロジェクト: m3y54m/32bitmicro
/*------------------------------------------------------------------------
 * objd2oid - take a object string and parse it into an object id
 *------------------------------------------------------------------------
 */
LOCAL int
objd2oid(
    char	*str,
    struct oid	*oip)
{
	register char	*cp;
	struct mib_info	*onp;
	int		idlen, len, i;
	char		tmp[BUFSIZE];

	idlen = 0;
	cp = str;
	if (isalpha(*str)) {
		/*
		 * The string at least starts out with object descriptors,
		 * and may have object ids at the end. So, first, find the
		 * end of the descriptors part.
		 */
		for (; *cp != '\0' && (isalpha(*cp) || *cp == '.'); cp++)
			 /* empty */;
		len = cp - str;
		if (*cp != '\0') 
			len--;

		for (i = 0; i < mib_entries; i++) {
			onp = &mib[i];
			strcpy(tmp, onp->mi_prefix);
			strcat(tmp, onp->mi_name);
			if (((int)strlen(tmp) == len) &&
			    (memcmp(tmp, str, len)==0))
				break;
		}
		if (i >= mib_entries)
			return SYSERR;

		idlen = oip->len = onp->mi_objid.len;
		memcpy(oip->id, onp->mi_objid.id, idlen*2);

		/* remove possible trailing ".0" */
		if (strequ(cp, "0"))
			return OK;
	}
	/* rest of variable name is object sub-id's */
	if (isdigit(*cp)) 
		oip->len = idlen + dot2oid(&oip->id[idlen], cp);
	return OK;
}
コード例 #19
0
ファイル: CELS.cpp プロジェクト: RamiroCruzo/freearc_src
// Central CELS function that provides all CELS services
int CELS_Call (TABI_ELEMENT* params)
{
  TABI_MAP p(params); p.dump();
  char *service = p._str("service");

  // ==== AUTO-SERVICES =====================================
  // Ignore zero mem parameter to Set* calls
  if (start_with (service, "Set") && isupper(service[3]))
    if (p._int("mem",1)==0)
      return p._return(p._str("method"));

  // Limit* = Set* if Get*>limit
  if (start_with (service, "Limit") && isupper(service[5]))                 return p._return(p._str("method"));   // to do: get & set
/*
  {
    char new_service[MAX_METHOD_STRLEN];
    sprintf(new_service, "Get%s", service+5);
    MemSize mem = TABI_callret(CELS_Call, TABI_DYNAMAP(p) ("service", new_service));
    if (mem <= p._longlong("mem"))         // if method already uses less memory than specified limit
      return p._return(p._str("method"));  // then return method unmodified
    sprintf(new_service, "Set%s", service+5);
    return TABI_call(CELS_Call, TABI_DYNAMAP(p) ("service", new_service));
  }
*/
  if (strequ (service, "encryption?"))               return 1;                             // to do: aes-specific
  if (start_with (p._str("method",""), "aes"))       return p._return(p._str("method"));   // to do: aes-specific
  //default: GetBlockSize        {return 0;}
  //default: SetBlockSize        {}
  // ========================================================

  // Find appropriate method to service this call
  for (int i=0; i<methodsCount; i++)
  {
    try
    {
      int x = methodsTable[i](params);
      if (x!=FREEARC_ERRCODE_NOT_IMPLEMENTED)
        return x;
    }
    catch (...)
    {
    }
  }
  return FREEARC_ERRCODE_NOT_IMPLEMENTED;
}
コード例 #20
0
ファイル: machine.cpp プロジェクト: alekstorm/tala
void Machine_initLookAndFeel (unsigned int argc, char **argv) {
	#if defined (sgi) || defined (sun)
	struct stat statBuf;
	#endif

	/*
	 * Determining the appropriate look-and-feel: the default depends on the client machine.
	 */
	#if defined (sgi)
		lookAndFeel = stat ("/usr/sbin/schemebr", & statBuf) ? LookAndFeel_MOTIF : LookAndFeel_SGI;
	#elif defined (sun4)
		lookAndFeel = LookAndFeel_SUN4;
	#elif defined (sun)
		lookAndFeel = stat ("/usr/dt/bin/dtaction", & statBuf) ? LookAndFeel_SOLARIS : LookAndFeel_CDE;
	#elif defined (HPUX)
		lookAndFeel = LookAndFeel_HP;
	#elif defined (macintosh)
		lookAndFeel = LookAndFeel_MAC;
		return;
	#elif defined (_WIN32)
		lookAndFeel = LookAndFeel_WIN32;
		return;
	#elif defined (linux)
		lookAndFeel = LookAndFeel_LINUX;
	#else
		lookAndFeel = LookAndFeel_MOTIF;
	#endif

	/*
	 * Command line may override the look-and-feel.
	 */
	if (argc > 1) {
		if (strequ (argv [1], "-sgi")) lookAndFeel = LookAndFeel_SGI;
		else if (strequ (argv [1], "-motif")) lookAndFeel = LookAndFeel_MOTIF;
		else if (strequ (argv [1], "-cde")) lookAndFeel = LookAndFeel_CDE;
		else if (strequ (argv [1], "-solaris")) lookAndFeel = LookAndFeel_SOLARIS;
		else if (strequ (argv [1], "-hp")) lookAndFeel = LookAndFeel_HP;
		else if (strequ (argv [1], "-sun4")) lookAndFeel = LookAndFeel_SUN4;
		else if (strequ (argv [1], "-mac")) lookAndFeel = LookAndFeel_MAC;
		else if (strequ (argv [1], "-linux")) lookAndFeel = LookAndFeel_LINUX;
	}
}
コード例 #21
0
ファイル: x_snmp.c プロジェクト: m3y54m/32bitmicro
/*------------------------------------------------------------------------
 * parsevalue - parse the type and value of variable to set
 *------------------------------------------------------------------------
 */
LOCAL int
parsevalue(char **word, struct snbentry *bl)
{
	if (strequ(*word, "int"))
		SVTYPE(bl) = ASN1_INT;
	else if (strequ(*word, "counter")) 
		SVTYPE(bl) = ASN1_COUNTER;
	else if (strequ(*word, "gauge")) 
		SVTYPE(bl) = ASN1_GAUGE;
	else if (strequ(*word, "timeticks")) 
		SVTYPE(bl) = ASN1_TIMETICKS;
	else if (strequ(*word, "str")) 
		SVTYPE(bl) = ASN1_OCTSTR;
	else if (strequ(*word, "objid")) 
		SVTYPE(bl) = ASN1_OBJID;
	else if (strequ(*word, "ipaddr")) 
		SVTYPE(bl) = ASN1_IPADDR;
	else
		return SYSERR;

	getword(word);
	if (**word == NULLCH)
		return SYSERR;

	switch (SVTYPE(bl)) {
	case ASN1_INT:
	case ASN1_COUNTER:
	case ASN1_GAUGE:
	case ASN1_TIMETICKS:
		SVINT(bl) = atoi(*word);
		break;
	case ASN1_OCTSTR:
		SVSTRLEN(bl) = strlen(*word);
		SVSTR(bl) = (char *) getmem(SVSTRLEN(bl));
		memcpy(SVSTR(bl), *word, SVSTRLEN(bl));
		break;
	case ASN1_OBJID:
		SVOIDLEN(bl) = dot2oid(SVOID(bl), *word);
		break;
	case ASN1_IPADDR:
		SVIPADDR(bl) = dot2ip(*word);
		break;
	default:
		return SYSERR;
	}
	return OK;
}
コード例 #22
0
int main() {
	char	s[1000000];
	while( scanf( "%s", s ) ) {
		if( *s == '.' ) break; 
		int	N = strlen( s );
		for( int i = 1; i <= N; i++) {
			if( N % i == 0 ) {
				int	M = N / i; 
				bool	match = 1;
				for( int j = 0; j < M; j++ ) {
					if( !strequ( s, s + j * i, i ) ) {
						match = 0;
						break; 
					}
				} 
				if( match ) {
					printf( "%d\n", M ); 
					break; 
				} 
			} 
		} 
	} 
} 
コード例 #23
0
ファイル: hexdate.c プロジェクト: doug16rogers/dr
// ---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
    int i;
    struct timeval           time;
    struct HEXON_TIME_STRUCT hexon;
    struct DAYSEC_STRUCT     daysec;

    gettimeofday(&time, NULL);
    set_epoch(DEFAULT_EPOCH);
    set_format(DEFAULT_FORMAT);

    for (i = 1; i < argc; i++)
    {
        char* argument = argv[i];
        if ((strcmp(argument, "--help") == 0) || (strcmp (argument, "-h") == 0)) usage();
        else if (strequ(argument, "--epoch=" )) set_epoch(strchr(argument, '=') + 1);
        else if (strequ(argument, "--format=")) set_format(strchr(argument, '=') + 1);
        else if (strequ(argument, "--verbose")) verbose = 1;
        else if ('-' == argument[0])
        {
            fprintf(stderr, PROGRAM_NAME ": *** error: unknown option \"%s\".\n\n", argument);
            usage();
        }
        else
        {
            if (time_count >= MAX_TIMES)
            {
                fprintf(stderr, PROGRAM_NAME ": limited to %d explicit times on command line; continuing.\n", MAX_TIMES);
                break;
            }

            time_list[time_count++] = argument;
        }
    }

    /*
     * If no time is specified, use now.
     */
    if (0 == time_count)
    {
        time_list[time_count++] = "now";
    }

    /*
     * Go through the list of times to check.
     */
    for (i = 0; i < time_count; i++)
    {
        if (!daysec_from_text(&daysec, time_list[i]))
        {
            fprintf(stderr, PROGRAM_NAME ": *** error: invalid time \"%s\".\n", null_check(time_list[i]));
            usage();
        }

        if (verbose)
        {
            printf("Unix time    (seconds.microseconds): %llu.%06lu (hex 0x%llx/0x%05lx.\n",
                   (long long) time.tv_sec, (long) time.tv_usec, (long long) time.tv_sec, (long) time.tv_usec);
            printf("Unix daysec  (days.seconds): %lu.%05lu (hex 0x%lx/0x%05lx.\n",
                   daysec.day, (long) daysec.sec, daysec.day, (long) daysec.sec);
            printf("Epoch daysec (days.seconds): %lu.%05lu (hex 0x%lx/0x%05lx.\n",
                   epoch.day, (long) epoch.sec, epoch.day, (long) epoch.sec);
        }

        daysec_sub(&daysec, &daysec, &epoch);

        if (verbose)
        {
            printf("Daysec since epoch  (days.seconds): %lu.%05lu (hex 0x%lx/0x%05lx.\n",
                   daysec.day, (long) daysec.sec, daysec.day, (long) daysec.sec);
        }

        Hexon_Set_Day_Second(&hexon, daysec.day, daysec.sec);

        if (verbose)
        {
            printf("Decimal hexon = %20.6f.\n", hexon.hexon);
        }

        if (!Hexon_Print(stdout, output_format, &hexon))
        {
            fprintf(stderr, PROGRAM_NAME ": *** error: could not print using format \"%s\".\n", null_check(output_format));
            return 1;
        }
    }   /* For each time to check */

    return 0;
}   // main
コード例 #24
0
ファイル: C_CLS.cpp プロジェクト: RamiroCruzo/freearc_src
// Записать в buf[MAX_METHOD_STRLEN] строку, описывающую метод сжатия и его параметры (функция, обратная к parse_CLS)
void CLS_METHOD::ShowCompressionMethod (char *buf)
{
    if (strequ(params,""))
      then strcpy (buf, name);
      else sprintf(buf, "%s:%s", name, params);
}
コード例 #25
0
ファイル: CELS.cpp プロジェクト: RamiroCruzo/freearc_src
int COMPRESSION_METHOD::server()
{
  char *service = p._str("service");

  // Global services
  if (strequ (service, "register"))               return FREEARC_OK; //to do: Register();

  // Invocation-specific services
  if (strequ (service, "decompress"))             {parse_method(); return decompress (p._callback("callback"), p);}
#ifndef FREEARC_DECOMPRESS_ONLY
  if (strequ (service, "compress"))               {parse_method(); return compress   (p._callback("callback"), p);}
  if (strequ (service, "canonize"))               {parse_method();                                     char a[1000]; ShowCompressionMethod(a); return p._return(a);}
  if (strequ (service, "SetCompressionMem"))      {parse_method(); SetCompressionMem  (p._int("mem")); char a[1000]; ShowCompressionMethod(a); return p._return(a);}
  if (strequ (service, "SetDictionary"))          {parse_method(); SetDictionary      (p._int("mem")); char a[1000]; ShowCompressionMethod(a); return p._return(a);}
  if (strequ (service, "SetBlockSize"))           {parse_method(); SetBlockSize       (p._int("mem")); char a[1000]; ShowCompressionMethod(a); return p._return(a);}
  if (strequ (service, "SetDecompressionMem"))    {parse_method(); SetDecompressionMem(p._int("mem")); char a[1000]; ShowCompressionMethod(a); return p._return(a);}
  if (strequ (service, "GetCompressionMem"))      {parse_method(); return p._return (GetCompressionMem());}
  if (strequ (service, "GetDictionary"))          {parse_method(); return p._return (GetDictionary());}
  if (strequ (service, "GetBlockSize"))           {parse_method(); return p._return (GetBlockSize());}
#endif
  if (strequ (service, "GetDecompressionMem"))    {parse_method(); return p._return (GetDecompressionMem());}

  return FREEARC_ERRCODE_NOT_IMPLEMENTED;
}
コード例 #26
0
ファイル: CELS.cpp プロジェクト: RamiroCruzo/freearc_src
 // Разбирает строку с параметрами метода
 virtual void parse_method()
 {
   if (!strequ (p._str("method"), "storing"))
     throw "STORING_METHOD:parse_method";
 }
コード例 #27
0
ファイル: main.cpp プロジェクト: nemequ/tornado
int main (int argc, char **argv)
{
    // Optimize allocation for Tornado (2GB hash allocated after 1GB dictionary)
    AllocTopDown = FALSE;

    // Operation mode
    OPMODE global_mode=AUTO;

    // Record that stores all the info required for ReadWriteCallback
    static Results r;
    r.use_cpu_time = r.quiet_title = r.quiet_header = r.quiet_progress = r.quiet_result = FALSE;

    // Default compression parameters are equivalent to option -5
    r.method = std_Tornado_method [default_Tornado_method];

    // Delete successfully (de)compressed input files
    bool delete_input_files = FALSE;

    // Count of files to process
    int fcount=0;

    // Output path/filename
    const char *output_filename = NULL;

    // Process options until "--"
    // 1. First, process -1..-16 option if any
    for (char **argv_ptr = argv; *++argv_ptr!=NULL; ) {
        char *param = *argv_ptr;
        if (*param == '-') {
            param++;
                 if (strcasecmp(param,"-")==0)   break;   // "--" is a "stop processing" option
            else if (isdigit(*param))            r.method = std_Tornado_method[check_parse_int (param, 1, elements(std_Tornado_method)-1, param-1)];
        }
    }
    // 2. Second, process rest of options
    for (char **argv_ptr = argv; *++argv_ptr!=NULL; ) {
        char *param = *argv_ptr;
        if (param[0] != '-' || param[1]=='\0') {
            fcount++;
        } else { param++;  int error=0;
                 if (strcasecmp(param,"-")==0)      break;
            else if (strcasecmp(param,"") ==0)      continue;
            else if (strcasecmp(param,"z")==0)      global_mode=_COMPRESS;
            else if (strcasecmp(param,"d")==0)      global_mode=_DECOMPRESS;
            else if (strcasecmp(param,"delete")==0) delete_input_files=TRUE;
            else if (strcasecmp(param,"t")==0)      output_filename="";
            else if (strcasecmp(param,"q")==0)      r.quiet_title = r.quiet_header = r.quiet_progress = r.quiet_result = TRUE;
#ifndef FREEARC_NO_TIMING
            else if (strcasecmp(param,"cpu")==0)    r.use_cpu_time=TRUE;
#endif
            else if (strcasecmp(param,"h")==0)      global_mode=HELP;
            else if (strcasecmp(param,"b")==0)      r.method.buffer = MAX_BUFFER_SIZE;         // set buffer size to the maximum supported by LZ coders
            else if (strcasecmp(param,"x")==0)      r.method.caching_finder = CACHING_MF4;
            else if (strcasecmp(param,"xx")==0)     r.method.caching_finder = CYCLED_MF4;
            else if (strcasecmp(param,"x+")==0)     r.method.caching_finder = CACHING_MF4;
            else if (strcasecmp(param,"x-")==0)     r.method.caching_finder = NON_CACHING_MF;
            else if (strcasecmp(param,"t+")==0)     r.method.find_tables = TRUE;
            else if (strcasecmp(param,"t-")==0)     r.method.find_tables = FALSE;
            else if (strcasecmp(param,"t1")==0)     r.method.find_tables = TRUE;
            else if (strcasecmp(param,"t0")==0)     r.method.find_tables = FALSE;
            else if (strcasecmp(param,"s")==0)      r.method.hash3 = 1;
            else if (strcasecmp(param,"ss")==0)     r.method.hash3 = 2;
            else if (strcasecmp(param,"s+")==0)     r.method.hash3 = 1;
            else if (strcasecmp(param,"s-")==0)     r.method.hash3 = 0;
            else if (start_with(param,"fb"))        r.method.fast_bytes = check_parse_int (param+2, MIN_FAST_BYTES, MAX_FAST_BYTES, *argv_ptr);
#ifdef FREEARC_WIN
            else if (strcasecmp(param,"slp-")==0)   DefaultLargePageMode = DISABLE;
            else if (strcasecmp(param,"slp" )==0)   DefaultLargePageMode = TRY;
            else if (strcasecmp(param,"slp+")==0)   DefaultLargePageMode = FORCE;
#endif
            else if (start_with(param,"rem"))       /* ignore option */;
            else if (isdigit(*param))            ; // -1..-16 option is already processed :)
            else switch( tolower(*param++) ) {
                case 'b': r.method.buffer          = check_parse_mem (param, MIN_BUFFER_SIZE, MAX_BUFFER_SIZE,    *argv_ptr);  break;
                case 'h': r.method.hashsize        = check_parse_mem (param, MIN_HASH_SIZE,   MAX_HASH_SIZE,      *argv_ptr);  break;
                case 'l': r.method.hash_row_width  = check_parse_int (param, 1,               MAX_HASH_ROW_WIDTH, *argv_ptr);  break;
                case 'u': r.method.update_step     = check_parse_int (param, 1,               MAX_UPDATE_STEP,    *argv_ptr);  break;
                case 'c': r.method.encoding_method = check_parse_int (param, BYTECODER,       ARICODER,           *argv_ptr);  break;
                case 's': r.method.hash3           = check_parse_int (param, 0,               2,                  *argv_ptr);  break;
                case 'p': r.method.match_parser    = parseInt (param, &error);  break;
                case 'x': r.method.caching_finder  = parseInt (param, &error);  break;
                case 'o': output_filename          = param;                     break;
                case 'q':
#ifndef FREEARC_NO_TIMING
                          r.quiet_title            = strchr (param, 't');
                          r.quiet_progress         = strchr (param, 'p');
#endif
                          r.quiet_header           = strchr (param, 'h');
                          r.quiet_result           = strchr (param, 'r');
                          break;
                case 'a': switch( tolower(*param++) ) {
                            case 'h': r.method.auxhash_size      = check_parse_mem (param, MIN_HASH_SIZE, MAX_HASH_SIZE, *argv_ptr);  goto check_for_errors;
                            case 'l': r.method.auxhash_row_width = check_parse_int (param, 1,        MAX_HASH_ROW_WIDTH, *argv_ptr);  goto check_for_errors;
                          }
                          // 'a' should be the last case!
                default : fprintf (stderr, "ERROR: unknown option '%s'\n", *argv_ptr);
                          exit(FREEARC_EXIT_ERROR);
            }
check_for_errors:
            if (error) {
                fprintf (stderr, "ERROR: bad option format: '%s'\n", *argv_ptr);
                exit(FREEARC_EXIT_ERROR);
            }
            if (!(r.method.match_parser==GREEDY || r.method.match_parser==LAZY  || r.method.match_parser==OPTIMAL)) {
                fprintf (stderr, "ERROR: bad option value: '%s'\n", *argv_ptr);
                exit(FREEARC_EXIT_ERROR);
            }
            int mf = r.method.caching_finder;
            r.method.caching_finder = mf = (mf==CACHING_MF4_DUB? CACHING_MF4 : (mf==CYCLED_MF4_DUB? CYCLED_MF4 : mf));
            if (!(mf==NON_CACHING_MF || (CYCLED_MF4<=mf && mf<=CYCLED_MF7) || (CACHING_MF4<=mf && mf<=CACHING_MF7) || (BT_MF4<=mf && mf<=BT_MF7))) {
                fprintf (stderr, "ERROR: non-existing match finder: '%s'\n", *argv_ptr);
                exit(FREEARC_EXIT_ERROR);
            }
        }
    }

    // No files to compress: read from stdin and write to stdout
    if (global_mode!=HELP && fcount==0 &&
       (global_mode!=AUTO  ||  !isatty(0) && !isatty(1)) ) {

        static char *_argv[] = {argv[0], (char*)"-", NULL};
        argv = _argv;
        fcount = 1;

    } else if (global_mode==HELP || fcount==0) {
        char h[100], ah[100], b[100], MinHashSizeStr[100], MaxHashSizeStr[100], MinBufSizeStr[100], MaxBufSizeStr[100];
        showMem64 (r.method.hashsize, h);
        showMem64 (r.method.auxhash_size, ah);
        showMem64 (r.method.buffer, b);
        showMem64 (MIN_HASH_SIZE, MinHashSizeStr);
        showMem64 (MAX_HASH_SIZE+1, MaxHashSizeStr);
        showMem64 (MIN_BUFFER_SIZE, MinBufSizeStr);
        showMem64 (MAX_BUFFER_SIZE, MaxBufSizeStr);
        printf( "Tornado compressor v0.6  (c) [email protected]  http://freearc.org  2014-03-08\n"
                "\n"
                " Usage: tor [options and files in any order]\n"
                "   -#      -- compression level (1..%d), default %d\n", int(elements(std_Tornado_method))-1, default_Tornado_method);
        printf( "   -z      -- force compression\n"
                "   -d      -- force decompression\n"
                "   -oNAME  -- output filename/directory (default %s/%s)\n", COMPRESS_EXT, DECOMPRESS_EXT);
        printf( "   -t      -- test (de)compression (redirect output to nul)\n"
                "   -delete -- delete successfully (de)compressed input files\n"
#ifdef FREEARC_NO_TIMING
                "   -q      -- be quiet; -q[hr]* disables header/results individually\n"
#else
                "   -q      -- be quiet; -q[thpr]* disables title/header/progress/results individually\n"
                "   -cpu    -- compute raw CPU time (for benchmarking)\n"
#endif
#ifdef FREEARC_WIN
                "   -slp[+/-/]   -- force/disable/try(default) large pages support (2mb/4mb)\n"
#endif
                "   -rem... -- command-line remark\n"
                "   -h      -- display this help\n"
                "   --      -- stop flags processing\n"
                " \"-\" used as filename means stdin/stdout\n"
                "\n"
                " Advanced compression parameters:\n"
                "   -b#     -- buffer size (%s..%s), default %s\n", MinBufSizeStr, MaxBufSizeStr, b);
        printf( "   -h#     -- hash size (%s..%s-1), default %s\n", MinHashSizeStr, MaxHashSizeStr, h);
        printf( "   -l#     -- length of hash row (1..%d), default %d\n", int(MAX_HASH_ROW_WIDTH), r.method.hash_row_width);
        printf( "   -ah#    -- auxiliary hash size (%s..%s-1), default %s\n", MinHashSizeStr, MaxHashSizeStr, ah);
        printf( "   -al#    -- auxiliary hash row length (1..%d), default %d\n", int(MAX_HASH_ROW_WIDTH), r.method.auxhash_row_width);
        printf( "   -u#     -- update step (1..%d), default %d\n", int(MAX_UPDATE_STEP), r.method.update_step);
        printf( "   -c#     -- coder (1-bytes, 2-bits, 3-huf, 4-arith), default %d\n", r.method.encoding_method);
        printf( "   -p#     -- parser (1-greedy, 2-lazy, 4-optimal), default %d\n", r.method.match_parser);
        printf( "   -x#     -- match finder (0: non-caching ht4, 4-7: cycling cached ht4..ht7,\n"
                "                            14-17: shifting cached ht4..ht7, 24-27: bt4..bt7), default %d\n", r.method.caching_finder);
        printf( "   -s#     -- 2/3-byte hash (0-disabled, 1-fast, 2-max), default %d\n", r.method.hash3);
        printf( "   -t#     -- table diffing (0-disabled, 1-enabled), default %d\n", r.method.find_tables);
        printf( "   -fb#    -- fast bytes in the optimal parser (%d..%d), default %d\n", int(MIN_FAST_BYTES), int(MAX_FAST_BYTES), r.method.fast_bytes);
        printf( "\n"
                " Predefined methods:\n");
        for (int i=1; i<elements(std_Tornado_method); i++)
        {
            printf("   %-8d-- %s\n", -i, name(std_Tornado_method[i]));
        }
        exit(EXIT_SUCCESS);
    }



    // (De)compress all files given on cmdline
    bool parse_options=TRUE;  // options will be parsed until "--"
    Install_signal_handler(signal_handler);

    for (char **parameters = argv; *++parameters!=NULL; )
    {
        // If options are still parsed and this argument starts with "-" - it's an option
        if (parse_options && parameters[0][0]=='-' && parameters[0][1]) {
            if (strequ(*parameters,"--"))  parse_options=FALSE;
            continue;
        }

        // Save input filename
        r.filename = *parameters;

        // Select operation mode if it was not specified on cmdline
        r.mode = global_mode != AUTO?                  global_mode :
                 end_with (r.filename, COMPRESS_EXT)?  _DECOMPRESS  :
                                                       _COMPRESS;
        // Extension that should be added to output filenames
        const char *MODE_EXT  =  r.mode==_COMPRESS? COMPRESS_EXT : DECOMPRESS_EXT;

        // Construct output filename
        if (r.mode==BENCHMARK  ||  output_filename && strequ (output_filename, "")) {  // Redirect output to nul
            strcpy (r.outname, "");
        } else if (output_filename) {
            if (strequ(output_filename,"-"))
                strcpy (r.outname, output_filename);
            else if (is_path_char (last_char (output_filename)))
                {sprintf(r.outname, "%s%s", output_filename, drop_dirname(r.filename));  goto add_remove_ext;}
            else if (dir_exists (output_filename))
                {sprintf(r.outname, "%s%c%s", output_filename, PATH_DELIMITER, drop_dirname(r.filename));  goto add_remove_ext;}
            else
                strcpy (r.outname, output_filename);
        } else if (strequ(r.filename,"-")) {
            strcpy (r.outname, r.filename);
        } else {
            // No output filename was given on cmdline:
            //    on compression   - add COMPRESS_EXT
            //    on decompression - remove COMPRESS_EXT (and add DECOMPRESS_EXT if file already exists)
            strcpy (r.outname, r.filename);
add_remove_ext: // Remove COMPRESS_EXT on the end of name or add DECOMPRESS_EXT (unless we are in _COMPRESS mode)
            if (r.mode!=_COMPRESS && end_with (r.outname, COMPRESS_EXT)) {
                r.outname [strlen(r.outname) - strlen(COMPRESS_EXT)] = '\0';
                if (file_exists (r.outname))
                    strcat(r.outname, MODE_EXT);
            } else {
                strcat(r.outname, MODE_EXT);
            }
        }

        // Open input file
        r.fin = strequ (r.filename, "-")? stdin : file_open_read_binary(r.filename);
        if (r.fin == NULL) {
            fprintf (stderr, "\n Can't open %s for read\n", r.filename);
            exit(FREEARC_EXIT_ERROR);
        }
        set_binary_mode (r.fin);

        // Open output file
        if (*r.outname) {
          r.fout = strequ (r.outname, "-")? stdout : file_open_write_binary(r.outname);
          if (r.fout == NULL) {
              fprintf (stderr, "\n Can't open %s for write\n", r.outname);
              exit(FREEARC_EXIT_ERROR);
          }
          set_binary_mode (r.fout);
        } else {
          r.fout = NULL;
        }

        // Prepare to (de)compression
        int result;  char filesize_str[100];
        start_print_stats(r);

        // Perform actual (de)compression
        switch (r.mode) {
        case _COMPRESS: {
            if (!r.quiet_header && r.filesize >= 0)
                fprintf (stderr, "Compressing %s bytes with %s\n", show3(r.filesize,filesize_str), name(r.method));
            PackMethod m = r.method;
            if (r.filesize >= 0)
                m.buffer = mymin (m.buffer, r.filesize+LOOKAHEAD*2);
            result = tor_compress (m, ReadWriteCallback, &r, NULL, -1);
            break; }

        case _DECOMPRESS: {
            //if (!r.quiet_header && !strequ (r.outname, "-"))   fprintf (stderr, "Unpacking %.3lf mb\n", double(r.filesize)/1000/1000);
            result = tor_decompress (ReadWriteCallback, &r, NULL, -1);
            break; }
        }

        // Finish (de)compression
        print_final_stats(r);
        fclose (r.fin);
        if (r.fout)  fclose (r.fout);

        if (result == FREEARC_OK)  {
            if (delete_input_files && !strequ(r.filename,"-"))    delete_file(r.filename);
        } else {
            if (!strequ(r.outname,"-") && !strequ(r.outname,""))  delete_file(r.outname);
            switch (result) {
            case FREEARC_ERRCODE_INVALID_COMPRESSOR:
                fprintf (stderr, "\nThis compression mode isn't supported by small Tornado version, use full version instead!");
                break;
            case FREEARC_ERRCODE_NOT_ENOUGH_MEMORY:
                fprintf (stderr, "\nNot enough memory for (de)compression!");
                break;
            case FREEARC_ERRCODE_READ:
                fprintf (stderr, "\nRead error! Bad media?");
                break;
            case FREEARC_ERRCODE_WRITE:
                fprintf (stderr, "\nWrite error! Disk full?");
                break;
            case FREEARC_ERRCODE_BAD_COMPRESSED_DATA:
                fprintf (stderr, "\nData can't be decompressed!");
                break;
            default:
                fprintf (stderr, "\n(De)compression failed with error code %d!", result);
                break;
            }
            exit(FREEARC_EXIT_ERROR);
        }

        // going to next file...
    }

    return EXIT_SUCCESS;
}
コード例 #28
0
ファイル: gtk.c プロジェクト: samhorlbeck/boggle-solver
int main(int argc, char *argv[])
{
    if(argc > 1)
    {
        if(strequ(argv[1], "--version"))
        {
            printf("Boggle Solver version 2.0\nBuild number %X\n", BUILDNUMBER);
            return 0;
        }
    }

    gdk_threads_init();

    // Load dictionary
    pthread_t dictThread;
    pthread_create(&dictThread, NULL, load_dict_threaded, NULL);
    pthread_detach(dictThread);

    GtkWidget *textbox_table, *solve_b, *clear_b, *list_scroll;

    gtk_init(&argc, &argv); //140

    window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
    gtk_container_set_border_width(GTK_CONTAINER(window), 10);
    gtk_widget_set_size_request(window, 653, 485);
    gtk_window_set_title(GTK_WINDOW(window), "Boggle Solver");

    gtk_signal_connect(GTK_OBJECT(window), "delete_event", GTK_SIGNAL_FUNC(delete_event), NULL);

    textbox_table = gtk_table_new(6, 5, FALSE);
    list = gtk_tree_view_new();

    list_scroll = gtk_scrolled_window_new(NULL, NULL);
    gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(list_scroll), GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);

    gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(list), FALSE);
    gtk_widget_set_size_request(list_scroll, 190, -1);
    gtk_container_add(GTK_CONTAINER(list_scroll), list);
    gtk_table_attach_defaults(GTK_TABLE(textbox_table), list_scroll, 4, 5, 0, 5);
    gtk_table_set_col_spacings(GTK_TABLE(textbox_table), 10);
    gtk_table_set_row_spacings(GTK_TABLE(textbox_table), 10);

    solve_b = gtk_button_new_with_label("Solve");
    clear_b = gtk_button_new_with_label("Clear");

    gtk_widget_set_size_request(solve_b, 100, 27);
    gtk_widget_set_size_request(clear_b, 100, 27);

    gtk_table_attach_defaults(GTK_TABLE(textbox_table), solve_b, 0, 1, 4, 5);
    gtk_table_attach_defaults(GTK_TABLE(textbox_table), clear_b, 3, 4, 4, 5);

    gtk_signal_connect(GTK_OBJECT(solve_b), "clicked", GTK_SIGNAL_FUNC(solve_clicked), NULL);
    gtk_signal_connect(GTK_OBJECT(clear_b), "clicked", GTK_SIGNAL_FUNC(clear_clicked), NULL);

    int x, y;
    for(x = 0; x < 4; x++)
    {
        for(y = 0; y < 4; y++)
        {
            textboxes[x][y] = gtk_entry_new();
            GtkWidget *tb = textboxes[x][y];
            int *idx = malloc(sizeof(int));
            *idx = y * 4 + x;
            gtk_entry_set_max_length(GTK_ENTRY(tb), 1);
            gtk_table_attach_defaults(GTK_TABLE(textbox_table), tb, x, x + 1, y, y + 1);
            gtk_entry_set_width_chars(GTK_ENTRY(tb), 5);
            gtk_entry_set_alignment(GTK_ENTRY(tb), 0.5);
            gtk_widget_set_size_request(tb, 100, 100);
            gtk_widget_modify_font(tb, pango_font_description_from_string("Ubuntu 55"));
            gtk_signal_connect(GTK_OBJECT(tb), "backspace", GTK_SIGNAL_FUNC(backspace_pressed), NULL);
            gtk_signal_connect(GTK_OBJECT(tb), "key-press-event", GTK_SIGNAL_FUNC(key_pressed), NULL);
            gtk_signal_connect(GTK_OBJECT(tb), "button-press-event", GTK_SIGNAL_FUNC(tb_focus), idx);
        }
    }

    gtk_container_add(GTK_CONTAINER(window), textbox_table);

    init_list(list);

    gtk_widget_show_all(window);

    gtk_main();

    dict_clean_up();

    gdk_threads_leave();

    return 0;
}
コード例 #29
0
	pipe(p_fd2);
	dup2(p_fd2[1], fd2);
	write(fd2, "www\nzzz\n", 12);
	dup2(out_fd2, fd2);

	char 	*line_fd3;
	int		p_fd3[2];
	int		fd3 = 3;
	int		out_fd3 = dup(fd3);
	pipe(p_fd3);
	dup2(p_fd3[1], fd3);
	write(fd3, "888\n999\n", 12);
	dup2(out_fd3, fd3);

	get_next_line(p0[0], &line0);
	UT_ASSERT(strequ(line0, "aaa"));

	get_next_line(p_fd1[0], &line_fd1);
	UT_ASSERT(strequ(line_fd1, "111"));

	get_next_line(p_fd2[0], &line_fd2);
	UT_ASSERT(strequ(line_fd2, "www"));

	get_next_line(p_fd3[0], &line_fd3);
	UT_ASSERT(strequ(line_fd3, "888"));

	get_next_line(p0[0], &line0);
	UT_ASSERT(strequ(line0, "bbb"));

	get_next_line(p_fd1[0], &line_fd1);
	UT_ASSERT(strequ(line_fd1, "222"));
コード例 #30
0
ファイル: hexpaper.c プロジェクト: doug16rogers/dr
// ---------------------------------------------------------------------------
void Load_Arguments (int argc, char* argv[])
{
  int i;

  for (i = 1; i < argc; i++)
  {
    char* argument = argv[i];

    if (*argument == '-') argument++;
    if (*argument == '-') argument++;
    if ((strcmp (argument, "help") == 0) || (strcmp (argument, "-h") == 0)) Usage();
    else if (strequ (argument, "color16=" )) Set_Color  (&line_info[4].rgb, Find_Char (argument, '=') + 1);
    else if (strequ (argument, "color8="  )) Set_Color  (&line_info[3].rgb, Find_Char (argument, '=') + 1);
    else if (strequ (argument, "color4="  )) Set_Color  (&line_info[2].rgb, Find_Char (argument, '=') + 1);
    else if (strequ (argument, "color2="  )) Set_Color  (&line_info[1].rgb, Find_Char (argument, '=') + 1);
    else if (strequ (argument, "color1="  )) Set_Color  (&line_info[0].rgb, Find_Char (argument, '=') + 1);
    else if (strequ (argument, "hlines="  )) Set_Int    (&horizontal_lines, Find_Char (argument, '=') + 1, "hlines");
    else if (strequ (argument, "hspace="  )) Set_Double (&horizontal_space, Find_Char (argument, '=') + 1, "hspace");
    else if (strequ (argument, "hstart="  )) Set_Double (&horizontal_start, Find_Char (argument, '=') + 1, "hstart");
    else if (strequ (argument, "vlines="  )) Set_Int    (&vertical_lines,   Find_Char (argument, '=') + 1, "vlines");
    else if (strequ (argument, "vspace="  )) Set_Double (&vertical_space,   Find_Char (argument, '=') + 1, "vspace");
    else if (strequ (argument, "vstart="  )) Set_Double (&vertical_start,   Find_Char (argument, '=') + 1, "vstart");
    else if (strequ (argument, "width16=" )) Set_Double (&line_info[4].width, Find_Char (argument, '=') + 1, "width10");
    else if (strequ (argument, "width8="  )) Set_Double (&line_info[3].width, Find_Char (argument, '=') + 1, "width08");
    else if (strequ (argument, "width4="  )) Set_Double (&line_info[2].width, Find_Char (argument, '=') + 1, "width04");
    else if (strequ (argument, "width2="  )) Set_Double (&line_info[1].width, Find_Char (argument, '=') + 1, "width02");
    else if (strequ (argument, "width1="  )) Set_Double (&line_info[0].width, Find_Char (argument, '=') + 1, "width01");
    else if (strequ (argument, "verbose")) verbose = 1;
    else
    {
      fprintf (stderr, PROGRAM_NAME ": *** error: unknown option \"%s\".\n\n", argument);
      Usage();
    }
  }
}   // Load_Arguments