您当前的位置:首页 > IT编程 > C++
| C语言 | Java | VB | VC | python | Android | TensorFlow | C++ | oracle | 学术与代码 | cnn卷积神经网络 | gnn | 图像修复 | Keras | 数据集 | Neo4j | 自然语言处理 | 深度学习 | 医学CAD | 医学影像 | 超参数 | pointnet | pytorch | 异常检测 | Transformers | 情感分类 | 知识图谱 |

自学教程:C++ strchr函数代码示例

51自学网 2021-06-03 08:28:00
  C++
这篇教程C++ strchr函数代码示例写得很实用,希望能帮到您。

本文整理汇总了C++中strchr函数的典型用法代码示例。如果您正苦于以下问题:C++ strchr函数的具体用法?C++ strchr怎么用?C++ strchr使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。

在下文中一共展示了strchr函数的26个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。

示例1: switch

//.........这里部分代码省略.........		}		break;		case GPAC_OTI_MEDIA_FFMPEG:			return "GPAC FFMPEG Private Audio";		case GPAC_OTI_AUDIO_EVRC_VOICE:			return "EVRC Voice";		case GPAC_OTI_AUDIO_SMV_VOICE:			return "SMV Voice";		case GPAC_OTI_AUDIO_AC3:			return "AC-3 audio";		case GPAC_OTI_AUDIO_EAC3:			return "Enhanced AC-3 Audio";		case GPAC_OTI_AUDIO_DRA:			return "DRA Audio";		case GPAC_OTI_AUDIO_ITU_G719:			return "ITU G719 Audio";		case GPAC_OTI_AUDIO_DTS_CA:			return "DTS Coherent Acoustics audio";		case GPAC_OTI_AUDIO_DTS_HD_HR:			return "DTS-HD High Resolution audio";		case GPAC_OTI_AUDIO_DTS_HD_MASTER:			return "DTS-HD Master audios";		default:			return "Unknown Audio Type";		}		break;	case GF_STREAM_MPEG7:		return "MPEG-7 Description";	case GF_STREAM_IPMP:		return "MPEG-4 IPMP";	case GF_STREAM_OCI:		return "MPEG-4 OCI";	case GF_STREAM_MPEGJ:		return "MPEG-4 MPEG-J";	case GF_STREAM_INTERACT:		return "MPEG-4 User Interaction";	case GF_STREAM_IPMP_TOOL:		return "MPEG-4 IPMP Tool";	case GF_STREAM_FONT:		return "MPEG-4 Font Data";	case GF_STREAM_TEXT:		return "MPEG-4 Streaming Text";	case GF_STREAM_ND_SUBPIC:		return "Nero Digital Subpicture";	case GF_STREAM_PRIVATE_SCENE:		switch (esd->decoderConfig->objectTypeIndication) {		case GPAC_OTI_PRIVATE_SCENE_GENERIC:		{			char *ext = strchr(esd->decoderConfig->decoderSpecificInfo->data + 4, '.');			if (!ext) return "GPAC Internal Scene Description";			ext += 1;			if (!strnicmp(ext, "bt", 2))				return "BT Scene Description";			if (!strnicmp(ext, "xmt", 2))				return "XMT Scene Description";			if (!strnicmp(ext, "wrl", 3))				return "VRML Scene Description";			if (!strnicmp(ext, "x3d", 3))				return "W3D Scene Description";			if (!strnicmp(ext, "x3dv", 4))				return "X3D Scene Description";			if (!strnicmp(ext, "swf", 3))				return "Flash (SWF) Scene Description";			if (!strnicmp(ext, "xsr", 3))				return "LASeR-ML Scene Description";			if (!strnicmp(ext, "wgt", 3))				return "W3C Widget Package";			if (!strnicmp(ext, "mgt", 3))				return "MPEG-U Widget Package";		}		return "GPAC Internal Scene Description";		case GPAC_OTI_PRIVATE_SCENE_SVG:			return "SVG";		case GPAC_OTI_PRIVATE_SCENE_LASER:			return "LASeR (XML)";		case GPAC_OTI_PRIVATE_SCENE_XBL:			return "XBL";		case GPAC_OTI_PRIVATE_SCENE_EPG:			return "DVB Event Information";		case GPAC_OTI_PRIVATE_SCENE_WGT:			return "W3C/MPEG-U Widget";		case GPAC_OTI_SCENE_SVG:			return "SVG over RTP";		case GPAC_OTI_SCENE_SVG_GZ:			return "SVG+gz over RTP";		case GPAC_OTI_SCENE_DIMS:			return "3GPP DIMS";		default:			return "Unknown Scene Description";		}		break;	case GF_STREAM_PRIVATE_MEDIA:		return "Opaque Decoder";	case GF_STREAM_4CC:		return gf_4cc_to_str(esd->decoderConfig->objectTypeIndication);	default:		return "Unknown Media Type";	}}
开发者ID:ezdev128,项目名称:gpac,代码行数:101,


示例2: memcpy

/*!*/xbShort xbDbf::PutField(const xbShort FieldNo, const char *buf) {  xbShort len, i;  char * startpos;  char * tp;           /*  target pointer */  const char * sp;        /*  source pointer */  if( FieldNo < 0 || FieldNo >= NoOfFields )    return XB_INVALID_FIELDNO;  if( DbfStatus != XB_UPDATED ){    DbfStatus = XB_UPDATED;    memcpy( RecBuf2, RecBuf, RecordLen );  }    if( SchemaPtr[FieldNo].Type == 'L' && !ValidLogicalData( buf ))    return XB_INVALID_DATA;  else if(( SchemaPtr[FieldNo].Type == 'F' || SchemaPtr[FieldNo].Type == 'N' )       && !ValidNumericData( buf ))     return XB_INVALID_DATA;  else if( SchemaPtr[FieldNo].Type == 'D' ){    xbDate d;    if( !d.DateIsValid( buf ))      return XB_INVALID_DATA;  }  if( SchemaPtr[FieldNo].Type == 'C' && SchemaPtr[FieldNo].NoOfDecs > 0 )    memset( SchemaPtr[FieldNo].Address, 0x20, SchemaPtr[FieldNo].LongFieldLen );  else    memset( SchemaPtr[FieldNo].Address, 0x20, SchemaPtr[FieldNo].FieldLen );  len = strlen( buf );  if(( SchemaPtr[FieldNo].Type == 'N' || SchemaPtr[FieldNo].Type == 'F')       && len > SchemaPtr[FieldNo].FieldLen )    return XB_INVALID_DATA;  else if( len > SchemaPtr[FieldNo].FieldLen )    len = SchemaPtr[FieldNo].FieldLen;  if( SchemaPtr[FieldNo].Type == 'F' || SchemaPtr[FieldNo].Type == 'N'       || SchemaPtr[FieldNo].Type == 'M') {    const char *sdp = strchr( buf, '.' ); /*  source decimal point */    len = 0;    sp =buf;    while( *sp && *sp != '.' ) { len++; sp++; }    if( SchemaPtr[FieldNo].NoOfDecs > 0 ){      /* do the right of decimal area */      tp = SchemaPtr[FieldNo].Address;      tp += SchemaPtr[FieldNo].FieldLen - SchemaPtr[FieldNo].NoOfDecs - 1;      *tp++ = '.';      sp = sdp;      if( sp ) sp++;      for( i = 0; i < SchemaPtr[FieldNo].NoOfDecs; i++ )        if( sp && *sp ) *tp++ = *sp++; else *tp++ = '0';       startpos= SchemaPtr[FieldNo].Address +                SchemaPtr[FieldNo].FieldLen -                SchemaPtr[FieldNo].NoOfDecs - len - 1;     }    else    {      startpos=SchemaPtr[FieldNo].Address+SchemaPtr[FieldNo].FieldLen-len;     }  }  else    startpos = SchemaPtr[FieldNo].Address;  memcpy( startpos, buf, len );  return 0;}
开发者ID:utech,项目名称:UtechLib,代码行数:74,


示例3: set_global_values

void set_global_values(const char *configuration_file){	if (!configuration_file)		return;	pmesg(LOG_INFO, __FILE__, __LINE__, "Loading configuration from '%s'/n", configuration_file);	oph_server_params = hashtbl_create(HASHTBL_KEY_NUMBER, NULL);	if (!oph_server_params)		return;	char tmp[OPH_MAX_STRING_SIZE];	char *value;	FILE *file = fopen(configuration_file, "r");	if (file) {		char key[OPH_MAX_STRING_SIZE], value2[OPH_MAX_STRING_SIZE];		while (fgets(tmp, OPH_MAX_STRING_SIZE, file)) {			if (strlen(tmp)) {				tmp[strlen(tmp) - 1] = '/0';				if (tmp[0] == OPH_COMMENT_MARK)					continue;	// Skip possible commented lines				value = strchr(tmp, OPH_SEPARATOR_KV[0]);				if (value) {					value++;					snprintf(key, value - tmp, "%s", tmp);					if (value[0]) {						if (value[0] == OPH_SUBSTITUTION_MARK && !strncasecmp(value + 1, OPH_SERVER_LOCATION_STR, strlen(OPH_SERVER_LOCATION_STR))) {							snprintf(value2, OPH_MAX_STRING_SIZE, "%s%s", oph_server_location, value + strlen(OPH_SERVER_LOCATION_STR) + 1);							value = value2;						}						hashtbl_insert(oph_server_params, key, value);					} else						hashtbl_insert(oph_server_params, key, "");					pmesg(LOG_DEBUG, __FILE__, __LINE__, "Read %s=%s/n", key, value);				}			}		}		fclose(file);	}	// Pre-process	if ((value = hashtbl_get(oph_server_params, OPH_SERVER_CONF_TIMEOUT)))		oph_server_timeout = strtol(value, NULL, 10);	if ((value = hashtbl_get(oph_server_params, OPH_SERVER_CONF_INACTIVITY_TIMEOUT)))		oph_server_inactivity_timeout = strtol(value, NULL, 10);	if ((value = hashtbl_get(oph_server_params, OPH_SERVER_CONF_WORKFLOW_TIMEOUT)))		oph_server_workflow_timeout = strtol(value, NULL, 10);	if ((value = hashtbl_get(oph_server_params, OPH_SERVER_CONF_SERVER_FARM_SIZE)))		oph_server_farm_size = (unsigned int) strtol(value, NULL, 10);	if ((value = hashtbl_get(oph_server_params, OPH_SERVER_CONF_QUEUE_SIZE)))		oph_server_queue_size = (unsigned int) strtol(value, NULL, 10);	if ((value = hashtbl_get(oph_server_params, OPH_SERVER_CONF_AUTO_RETRY)))		oph_auto_retry = (unsigned int) strtol(value, NULL, 10);	if ((value = hashtbl_get(oph_server_params, OPH_SERVER_CONF_POLL_TIME)))		oph_server_poll_time = (unsigned int) strtol(value, NULL, 10);	if ((value = hashtbl_get(oph_server_params, OPH_SERVER_CONF_BASE_BACKOFF)))		oph_base_backoff = (unsigned int) strtol(value, NULL, 10);	if (!logfile && (value = hashtbl_get(oph_server_params, OPH_SERVER_CONF_LOGFILE))) {		pmesg(LOG_INFO, __FILE__, __LINE__, "Selected log file '%s'/n", value);		logfile = fopen(value, "a");		if (logfile)			set_log_file(logfile);		// Redirect stdout and stderr to logfile		if (!freopen(value, "a", stdout))			pmesg(LOG_ERROR, __FILE__, __LINE__, "Error in redirect stdout to logfile/n");		if (!freopen(value, "a", stderr))			pmesg(LOG_ERROR, __FILE__, __LINE__, "Error in redirect stderr to logfile/n");	}	// Default values	if (!oph_server_protocol && !(oph_server_protocol = hashtbl_get(oph_server_params, OPH_SERVER_CONF_PROTOCOL))) {		hashtbl_insert(oph_server_params, OPH_SERVER_CONF_PROTOCOL, OPH_DEFAULT_PROTOCOL);		oph_server_protocol = hashtbl_get(oph_server_params, OPH_SERVER_CONF_PROTOCOL);	}	if (!oph_server_host && !(oph_server_host = hashtbl_get(oph_server_params, OPH_SERVER_CONF_HOST))) {		if (!gethostname(tmp, OPH_MAX_STRING_SIZE))			hashtbl_insert(oph_server_params, OPH_SERVER_CONF_HOST, tmp);		else			hashtbl_insert(oph_server_params, OPH_SERVER_CONF_HOST, OPH_DEFAULT_HOST);		oph_server_host = hashtbl_get(oph_server_params, OPH_SERVER_CONF_HOST);	}	if (!oph_server_port && !(oph_server_port = hashtbl_get(oph_server_params, OPH_SERVER_CONF_PORT))) {		hashtbl_insert(oph_server_params, OPH_SERVER_CONF_PORT, OPH_DEFAULT_PORT);		oph_server_port = hashtbl_get(oph_server_params, OPH_SERVER_CONF_PORT);	}	if (!(oph_server_cert = hashtbl_get(oph_server_params, OPH_SERVER_CONF_CERT))) {		snprintf(tmp, OPH_MAX_STRING_SIZE, OPH_SERVER_CERT, oph_server_location);		hashtbl_insert(oph_server_params, OPH_SERVER_CONF_CERT, tmp);		oph_server_cert = hashtbl_get(oph_server_params, OPH_SERVER_CONF_CERT);	}	if (!(oph_server_ca = hashtbl_get(oph_server_params, OPH_SERVER_CONF_CA))) {		snprintf(tmp, OPH_MAX_STRING_SIZE, OPH_SERVER_CA, oph_server_location);		hashtbl_insert(oph_server_params, OPH_SERVER_CONF_CA, tmp);		oph_server_ca = hashtbl_get(oph_server_params, OPH_SERVER_CONF_CA);	}	if (!(oph_server_password = hashtbl_get(oph_server_params, OPH_SERVER_CONF_CERT_PASSWORD))) {		hashtbl_insert(oph_server_params, OPH_SERVER_CONF_CERT_PASSWORD, OPH_SERVER_PASSWORD);		oph_server_password = hashtbl_get(oph_server_params, OPH_SERVER_CONF_CERT_PASSWORD);	}	if (!(oph_rmanager_conf_file = hashtbl_get(oph_server_params, OPH_SERVER_CONF_RMANAGER_CONF_FILE))) {		snprintf(tmp, OPH_MAX_STRING_SIZE, OPH_RMANAGER_CONF_FILE, oph_server_location);		hashtbl_insert(oph_server_params, OPH_SERVER_CONF_RMANAGER_CONF_FILE, tmp);		oph_rmanager_conf_file = hashtbl_get(oph_server_params, OPH_SERVER_CONF_RMANAGER_CONF_FILE);//.........这里部分代码省略.........
开发者ID:OphidiaBigData,项目名称:ophidia-server,代码行数:101,


示例4: tcl_mv_cp

static int tcl_mv_cp(Tcl_Interp *irp, int argc, char **argv, int copy){  char *p, *fn = NULL, *oldpath = NULL, *s = NULL, *s1 = NULL;  char *newfn = NULL, *newpath = NULL;  int ok = 0, only_first, skip_this;  FILE *fdb_old, *fdb_new;  filedb_entry *fdbe_old, *fdbe_new;  long where;  BADARGS(3, 3, " oldfilepath newfilepath");  malloc_strcpy(fn, argv[1]);  p = strrchr(fn, '/');  if (p != NULL) {    *p = 0;    malloc_strcpy(s, fn);    strcpy(fn, p + 1);    if (!resolve_dir("/", s, &oldpath, -1)) {      /* Tcl can do * anything */      Tcl_AppendResult(irp, "-1", NULL);        /* Invalid source */      my_free(fn);      my_free(oldpath);      return TCL_OK;    }    my_free(s);  } else    malloc_strcpy(oldpath, "/");  malloc_strcpy(s, argv[2]);  if (!resolve_dir("/", s, &newpath, -1)) {    /* Destination is not just a directory */    p = strrchr(s, '/');    if (!p) {      malloc_strcpy(newfn, s);      s[0] = 0;    } else {      *p = 0;      malloc_strcpy(newfn, p + 1);    }    my_free(newpath);    if (!resolve_dir("/", s, &newpath, -1)) {      Tcl_AppendResult(irp, "-2", NULL);        /* Invalid desto */      my_free(newpath);      my_free(s);      my_free(newfn);      return TCL_OK;    }  } else    malloc_strcpy(newfn, "");  my_free(s);  /* Stupidness checks */  if ((!strcmp(oldpath, newpath)) && (!newfn[0] || !strcmp(newfn, fn))) {    my_free(newfn);    my_free(fn);    my_free(oldpath);    my_free(newpath);    Tcl_AppendResult(irp, "-3", NULL);  /* Stupid copy to self */    return TCL_OK;  }  /* Be aware of 'cp * this.file' possibility: ONLY COPY FIRST ONE */  if ((strchr(fn, '?') || strchr(fn, '*')) && newfn[0])    only_first = 1;  else    only_first = 0;  fdb_old = filedb_open(oldpath, 0);  if (!strcmp(oldpath, newpath))    fdb_new = fdb_old;  else    fdb_new = filedb_open(newpath, 0);  if (!fdb_old || !fdb_new) {    my_free(newfn);    my_free(fn);    my_free(oldpath);    my_free(newpath);    if (fdb_old)      filedb_close(fdb_old);    else if (fdb_new)      filedb_close(fdb_new);    Tcl_AppendResult(irp, "-5", NULL);  /* DB access failed */    return -1;  }  filedb_readtop(fdb_old, NULL);  fdbe_old = filedb_matchfile(fdb_old, ftell(fdb_old), fn);  if (!fdbe_old) {    my_free(newfn);    my_free(fn);    my_free(oldpath);    my_free(newpath);    if (fdb_new != fdb_old)      filedb_close(fdb_new);    filedb_close(fdb_old);    Tcl_AppendResult(irp, "-4", NULL);  /* No match */    return -2;  }  while (fdbe_old) {    where = ftell(fdb_old);    skip_this = 0;    if (!(fdbe_old->stat & (FILE_HIDDEN | FILE_DIR))) {//.........这里部分代码省略.........
开发者ID:Estella,项目名称:eggdrop-1.7,代码行数:101,


示例5: mant_exp

/* HBB 20010121: added code that attempts to fix rounding-induced * off-by-one errors in 10^%T and similar output formats */static voidmant_exp(    double log10_base,    double x,    TBOOLEAN scientific,	/* round to power of 3 */    double *m,			/* results */    int *p,    const char *format)		/* format string for fixup */{    int sign = 1;    double l10;    int power;    double mantissa;    /*{{{  check 0 */    if (x == 0) {	if (m)	    *m = 0;	if (p)	    *p = 0;	return;    }    /*}}} */    /*{{{  check -ve */    if (x < 0) {	sign = (-1);	x = (-x);    }    /*}}} */    l10 = log10(x) / log10_base;    power = floor(l10);    mantissa = pow(10.0, log10_base * (l10 - power));    /* round power to an integer multiple of 3, to get what's     * sometimes called 'scientific' or 'engineering' notation. Also     * useful for handling metric unit prefixes like 'kilo' or 'micro'     * */    if (scientific) {	/* Scientific mode makes no sense whatsoever if the base of	 * the logarithmic axis is anything but 10.0 */	assert(log10_base == 1.0);	/* HBB FIXED 20040701: negative modulo positive may yield	 * negative result.  But we always want an effectively	 * positive modulus --> adjust input by one step */	switch (power % 3) {	case -1:	    power -= 3;	case 2:	    mantissa *= 100;	    break;	case -2:	    power -= 3;	case 1:	    mantissa *= 10;	    break;	case 0:	    break;	default:	    int_error (NO_CARET, "Internal error in scientific number formatting");	}	power -= (power % 3);    }    /* HBB 20010121: new code for decimal mantissa fixups.  Looks at     * format string to see how many decimals will be put there.  Iff     * the number is so close to an exact power of 10 that it will be     * rounded up to 10.0e??? by an sprintf() with that many digits of     * precision, increase the power by 1 to get a mantissa in the     * region of 1.0.  If this handling is not wanted, pass NULL as     * the format string */    /* HBB 20040521: extended to also work for bases other than 10.0 */    if (format) {	double actual_base = (scientific ? 1000 : pow(10.0, log10_base));	int precision = 0;	double tolerance;	format = strchr (format, '.');	if (format != NULL)	    /* a decimal point was found in the format, so use that	     * precision. */	    precision = strtol(format + 1, NULL, 10);	/* See if mantissa would be right on the border.  The	 * condition to watch out for is that the mantissa is within	 * one printing precision of the next power of the logarithm	 * base.  So add the 0.5*10^-precision to the mantissa, and	 * see if it's now larger than the base of the scale */	tolerance = pow(10.0, -precision) / 2;	if (mantissa + tolerance >= actual_base) {	    mantissa /= actual_base;	    power += (scientific ? 3 : 1);	}    }    if (m)	*m = sign * mantissa;    if (p)//.........这里部分代码省略.........
开发者ID:asherliu,项目名称:gnuplot,代码行数:101,


示例6: TestFontClusters

int32_t TestFontClusters(void){#ifdef _USE_LEO_    int32_t          name;    int            i,j;    int            nClust;    int            porog=50; // test !!!    int            numInvalid;    LeoFieldSetup  fs={0};    RecRaster   rec;    RecObject   ro={0};    LeoPageSetup ps={0};    ClustInfo cluInfo;    uchar addLet,resLet;#ifdef _SAVE_INVALID_CLU_    FILE          *fp;#endif    curNumFile++;    nClust=FONGetClustCount();    set_alphabet(alphabet1, alpha_str);#ifdef _SAVE_INVALID_CLU_    fp=fopen("clust.tst","at");    fprintf(fp,"file %d/n",curNumFile);#endif    LEOSetPlatform(LEOGetCPU());    fs.nStyle = LS_PRINT;    memcpy(fs.AlphaTable,alphabet1,256);    LEOSetupField(&fs);    for(i=0,numInvalid=0;i<nClust;i++)    {        cluInfo.let = 0;        j=FONGetClustInfo(&cluInfo,i+1);        if(j<=0)            continue;        if(cluInfo.attr & CTB_PRINT_ITALIC)            continue;        if(cluInfo.attr & CTB_PRINT_BOLD)            continue;        // now - test only russian ASCII letters        if(cluInfo.let < 128 ||           cluInfo.let >= 176 && cluInfo.let < 224 ||           cluInfo.let > 240           )            continue;        addLet=(cluInfo.let < 144 ? cluInfo.let +32 :                cluInfo.let < 160 ? cluInfo.let +80 :                cluInfo.let < 176 ? cluInfo.let -32 :                cluInfo.let - 80                );        name=0;        FONGetClusterAsBW(&name,i,porog,&rec);        memset(&ro,0,sizeof(RecObject));        memcpy(&ro.recData.recRaster,&rec,sizeof(RecRaster));        ps.nIdPage=-1;        ro.recData.lwStatus=0;        LEOSetupPage(&ps);        LEORecogPrintChar(&ro);        // ничего хорошего по LEO ?        if( ro.recResults.lnAltCnt <= 0 ||            ro.recResults.Alt[0].Prob < 150            )            continue;        for(j=0;j<ro.recResults.lnAltCnt;j++)        {            resLet = stdAnsiToAscii(ro.recResults.Alt[j].Code);            if( resLet == cluInfo.let ||                resLet == addLet )                break;        }        if(j==0)            continue;        { char *qq;            resLet = stdAnsiToAscii(ro.recResults.Alt[0].Code);            if( !is_lower(resLet) )                resLet =  to_lower(resLet);            if( (qq=strchr(hasNearSame,cluInfo.let)) &&                NearSame[qq-(char*)hasNearSame] == resLet                )                continue;//.........这里部分代码省略.........
开发者ID:PauloMigAlmeida,项目名称:cuneiform,代码行数:101,


示例7: fw_parse_opt

static int fw_parse_opt(struct filter_util *qu, char *handle, int argc, char **argv, struct nlmsghdr *n){	struct tc_police tp;	struct tcmsg *t = NLMSG_DATA(n);	struct rtattr *tail;	__u32 mask = 0;	int mask_set = 0;	memset(&tp, 0, sizeof(tp));	if (handle) {		char *slash;		if ((slash = strchr(handle, '/')) != NULL)			*slash = '/0';		if (get_u32(&t->tcm_handle, handle, 0)) {			fprintf(stderr, "Illegal /"handle/"/n");			return -1;		}		if (slash) {			if (get_u32(&mask, slash+1, 0)) {				fprintf(stderr, "Illegal /"handle/" mask/n");				return -1;			}			mask_set = 1;		}	}	if (argc == 0)		return 0;	tail = NLMSG_TAIL(n);	addattr_l(n, 4096, TCA_OPTIONS, NULL, 0);	if (mask_set)		addattr32(n, MAX_MSG, TCA_FW_MASK, mask);	while (argc > 0) {		if (matches(*argv, "classid") == 0 ||		    matches(*argv, "flowid") == 0) {			unsigned handle;			NEXT_ARG();			if (get_tc_classid(&handle, *argv)) {				fprintf(stderr, "Illegal /"classid/"/n");				return -1;			}			addattr_l(n, 4096, TCA_FW_CLASSID, &handle, 4);		} else if (matches(*argv, "police") == 0) {			NEXT_ARG();			if (parse_police(&argc, &argv, TCA_FW_POLICE, n)) {				fprintf(stderr, "Illegal /"police/"/n");				return -1;			}			continue;		} else if (matches(*argv, "action") == 0) {			NEXT_ARG();			if (parse_action(&argc, &argv, TCA_FW_ACT, n)) {				fprintf(stderr, "Illegal fw /"action/"/n");				return -1;			}			continue;		} else if (strcmp(*argv, "indev") == 0) {			char d[IFNAMSIZ+1];			memset(d, 0, sizeof (d));			argc--;			argv++;			if (argc < 1) {				fprintf(stderr, "Illegal indev/n");				return -1;			}			strncpy(d, *argv, sizeof (d) - 1);			addattr_l(n, MAX_MSG, TCA_FW_INDEV, d, strlen(d) + 1);		} else if (strcmp(*argv, "help") == 0) {			explain();			return -1;		} else {			fprintf(stderr, "What is /"%s/"?/n", *argv);			explain();			return -1;		}		argc--; argv++;	}	tail->rta_len = (void *) NLMSG_TAIL(n) - (void *) tail;	return 0;}
开发者ID:qtekfun,项目名称:htcDesire820Kernel,代码行数:84,


示例8: recognized_connection_string

/* * Recognized connection string either starts with a valid URI prefix or * contains a "=" in it. * * Must be consistent with parse_connection_string: anything for which this * returns true should at least look like it's parseable by that routine. * * XXX This is a duplicate of the eponymous libpq function. */boolrecognized_connection_string(const char *connstr){	return uri_prefix_length(connstr) != 0 || strchr(connstr, '=') != NULL;}
开发者ID:MohammadHabbab,项目名称:postgres,代码行数:14,


示例9: virLXCProcessReadLogOutputData

static intvirLXCProcessReadLogOutputData(virDomainObjPtr vm,                               int fd,                               char *buf,                               size_t buflen){    int retries = 10;    int got = 0;    int ret = -1;    char *filter_next = buf;    buf[0] = '/0';    while (retries) {        ssize_t bytes;        bool isdead = false;        char *eol;        if (vm->pid <= 0 ||            (kill(vm->pid, 0) == -1 && errno == ESRCH))            isdead = true;        /* Any failures should be detected before we read the log, so we         * always have something useful to report on failure. */        bytes = saferead(fd, buf+got, buflen-got-1);        if (bytes < 0) {            virReportSystemError(errno, "%s",                                 _("Failure while reading log output"));            goto cleanup;        }        got += bytes;        buf[got] = '/0';        /* Filter out debug messages from intermediate libvirt process */        while ((eol = strchr(filter_next, '/n'))) {            *eol = '/0';            if (virLXCProcessIgnorableLogLine(filter_next)) {                memmove(filter_next, eol + 1, got - (eol - buf));                got -= eol + 1 - filter_next;            } else {                filter_next = eol + 1;                *eol = '/n';            }        }        if (got == buflen-1) {            virReportError(VIR_ERR_INTERNAL_ERROR,                           _("Out of space while reading log output: %s"),                           buf);            goto cleanup;        }        if (isdead) {            ret = got;            goto cleanup;        }        usleep(100*1000);        retries--;    }    virReportError(VIR_ERR_INTERNAL_ERROR,                   _("Timed out while reading log output: %s"),                   buf); cleanup:    return ret;}
开发者ID:candhare,项目名称:libvirt,代码行数:69,


示例10: parse_extended_opts

static void parse_extended_opts(struct ext2_super_block *param, 				const char *opts){	char	*buf, *token, *next, *p, *arg, *badopt = "";	int	len;	int	r_usage = 0;	len = strlen(opts);	buf = malloc(len+1);	if (!buf) {		fprintf(stderr,			_("Couldn't allocate memory to parse options!/n"));		exit(1);	}	strcpy(buf, opts);	for (token = buf; token && *token; token = next) {		p = strchr(token, ',');		next = 0;		if (p) {			*p = 0;			next = p+1;		}		arg = strchr(token, '=');		if (arg) {			*arg = 0;			arg++;		}		if (strcmp(token, "stride") == 0) {			if (!arg) {				r_usage++;				badopt = token;				continue;			}			param->s_raid_stride = strtoul(arg, &p, 0);			if (*p || (param->s_raid_stride == 0)) {				fprintf(stderr,					_("Invalid stride parameter: %s/n"),					arg);				r_usage++;				continue;			}		} else if (strcmp(token, "stripe-width") == 0 ||			   strcmp(token, "stripe_width") == 0) {			if (!arg) {				r_usage++;				badopt = token;				continue;			}			param->s_raid_stripe_width = strtoul(arg, &p, 0);			if (*p || (param->s_raid_stripe_width == 0)) {				fprintf(stderr,					_("Invalid stripe-width parameter: %s/n"),					arg);				r_usage++;				continue;			}		} else if (!strcmp(token, "resize")) {			unsigned long resize, bpg, rsv_groups;			unsigned long group_desc_count, desc_blocks;			unsigned int gdpb, blocksize;			int rsv_gdb;			if (!arg) {				r_usage++;				badopt = token;				continue;			}			resize = parse_num_blocks(arg, 						  param->s_log_block_size);			if (resize == 0) {				fprintf(stderr, 					_("Invalid resize parameter: %s/n"),					arg);				r_usage++;				continue;			}			if (resize <= param->s_blocks_count) {				fprintf(stderr, 					_("The resize maximum must be greater "					  "than the filesystem size./n"));				r_usage++;				continue;			}			blocksize = EXT2_BLOCK_SIZE(param);			bpg = param->s_blocks_per_group;			if (!bpg)				bpg = blocksize * 8;			gdpb = blocksize / sizeof(struct ext2_group_desc);			group_desc_count = 				ext2fs_div_ceil(param->s_blocks_count, bpg);			desc_blocks = (group_desc_count +				       gdpb - 1) / gdpb;			rsv_groups = ext2fs_div_ceil(resize, bpg);			rsv_gdb = ext2fs_div_ceil(rsv_groups, gdpb) - 				desc_blocks;			if (rsv_gdb > (int) EXT2_ADDR_PER_BLOCK(param))				rsv_gdb = EXT2_ADDR_PER_BLOCK(param);//.........这里部分代码省略.........
开发者ID:flwh,项目名称:Alcatel_OT_985_kernel,代码行数:101,


示例11: str_format

static int str_format (lua_State *L) {  int arg = 1;  size_t sfl;  const char *strfrmt = luaL_checklstring(L, arg, &sfl);  const char *strfrmt_end = strfrmt+sfl;  luaL_Buffer b;  luaL_buffinit(L, &b);  while (strfrmt < strfrmt_end) {    if (*strfrmt != L_ESC)      luaL_addchar(&b, *strfrmt++);    else if (*++strfrmt == L_ESC)      luaL_addchar(&b, *strfrmt++);  /* %% */    else { /* format item */      char form[MAX_FORMAT];  /* to store the format (`%...') */      char buff[MAX_ITEM];  /* to store the formatted item */      arg++;      strfrmt = scanformat(L, strfrmt, form);      switch (*strfrmt++) {        case 'c': {          sprintf(buff, form, (int)luaL_checknumber(L, arg));          break;        }        case 'd':  case 'i': {          addintlen(form);          sprintf(buff, form, (LUA_INTFRM_T)luaL_checknumber(L, arg));          break;        }        case 'o':  case 'u':  case 'x':  case 'X': {          addintlen(form);          sprintf(buff, form, (unsigned LUA_INTFRM_T)luaL_checknumber(L, arg));          break;        }        case 'e':  case 'E': case 'f':        case 'g': case 'G': {          sprintf(buff, form, (double)luaL_checknumber(L, arg));          break;        }        case 'q': {          addquoted(L, &b, arg);          continue;  /* skip the 'addsize' at the end */        }        case 's': {          size_t l;          const char *s = luaL_checklstring(L, arg, &l);          if (!strchr(form, '.') && l >= 100) {            /* no precision and string is too long to be formatted;               keep original string */            lua_pushvalue(L, arg);            luaL_addvalue(&b);            continue;  /* skip the `addsize' at the end */          }          else {            sprintf(buff, form, s);            break;          }        }        default: {  /* also treat cases `pnLlh' */          return luaL_error(L, "invalid option " LUA_QL("%%%c") " to "                               LUA_QL("format"), *(strfrmt - 1));        }      }      luaL_addlstring(&b, buff, strlen(buff));    }  }  luaL_pushresult(&b);  return 1;}
开发者ID:Desch,项目名称:Arcemu-2.4.3,代码行数:67,


示例12: __read

static int __read(RIO *io, RIODesc *fd, ut8 *buf, int count) {	char fmt[4096], num[128];	int rv, rescount = -1;	int bufi, numi;	char *res, *r;	if (!fd || !fd->data) {		return -1;	}	if (count > 1024) {		count = 1024;	}	snprintf (fmt, sizeof (fmt),		"{/"op/":/"read/",/"address/":%"PFMT64d",/"count/":%d}",		io->off, count);	rv = r2p_write (R2P (fd), fmt);	if (rv < 1) {		eprintf ("r2p_write: error/n");		return -1;	}	res = r2p_read (R2P (fd));	/* TODO: parse json back */	r = strstr (res, "result");	if (r) {		rescount = atoi (r + 6 + 2);	}	r = strstr (res, "data");	if (r) {		char *arr = strchr (r, ':');		if (!arr || arr[1]!='[') {			goto beach;		}		arr += 2;		for (num[0] = numi = bufi = 0; bufi < count && *arr; arr++) {			switch (*arr) {			case '0':			case '1':			case '2':			case '3':			case '4':			case '5':			case '6':			case '7':			case '8':			case '9':				num[numi++] = *arr;				num[numi] = 0;				break;			case ' ':			case ',':			case ']':				if (num[0]) {					buf[bufi++] = atoi (num);					num[numi = 0] = 0;				}				break;			case 'n':			case 'u':			case 'l':				break;			default:				goto beach;				break;			}		}	}beach:	free (res);	return rescount;}
开发者ID:mrexodia,项目名称:radare2,代码行数:70,


示例13: pipe_read_line

//.........这里部分代码省略.........		CloseHandle(childstdoutrd);		CloseHandle(childstdoutwr);		return NULL;	}	CloseHandle(childstdoutrd);	ZeroMemory(&pi, sizeof(pi));	ZeroMemory(&si, sizeof(si));	si.cb = sizeof(si);	si.dwFlags = STARTF_USESTDHANDLES;	si.hStdError = childstdoutwr;	si.hStdOutput = childstdoutwr;	si.hStdInput = INVALID_HANDLE_VALUE;	if (CreateProcess(NULL,					  cmd,					  NULL,					  NULL,					  TRUE,					  0,					  NULL,					  NULL,					  &si,					  &pi))	{		/* Successfully started the process */		char	   *lineptr;		ZeroMemory(line, maxsize);		/* Try to read at least one line from the pipe */		/* This may require more than one wait/read attempt */		for (lineptr = line; lineptr < line + maxsize - 1;)		{			DWORD		bytesread = 0;			/* Let's see if we can read */			if (WaitForSingleObject(childstdoutrddup, 10000) != WAIT_OBJECT_0)				break;			/* Timeout, but perhaps we got a line already */			if (!ReadFile(childstdoutrddup, lineptr, maxsize - (lineptr - line),						  &bytesread, NULL))				break;			/* Error, but perhaps we got a line already */			lineptr += strlen(lineptr);			if (!bytesread)				break;			/* EOF */			if (strchr(line, '/n'))				break;			/* One or more lines read */		}		if (lineptr != line)		{			/* OK, we read some data */			int			len;			/* If we got more than one line, cut off after the first /n */			lineptr = strchr(line, '/n');			if (lineptr)				*(lineptr + 1) = '/0';			len = strlen(line);			/*			 * If EOL is /r/n, convert to just /n. Because stdout is a			 * text-mode stream, the /n output by the child process is			 * received as /r/n, so we convert it to /n.  The server main.c			 * sets setvbuf(stdout, NULL, _IONBF, 0) which has the effect of			 * disabling /n to /r/n expansion for stdout.			 */			if (len >= 2 && line[len - 2] == '/r' && line[len - 1] == '/n')			{				line[len - 2] = '/n';				line[len - 1] = '/0';				len--;			}			/*			 * We emulate fgets() behaviour. So if there is no newline at the			 * end, we add one...			 */			if (len == 0 || line[len - 1] != '/n')				strcat(line, "/n");			retval = line;		}		CloseHandle(pi.hProcess);		CloseHandle(pi.hThread);	}	CloseHandle(childstdoutwr);	CloseHandle(childstdoutrddup);	return retval;#endif   /* WIN32 */}
开发者ID:42penguins,项目名称:postgres,代码行数:101,


示例14: tr

QString QDictWidget::searchExpr(const QString &expr, int maxResults){    if(!ensureDictFile())    {        return "";    }    if(!dictFile.open(QFile::ReadOnly))    {        return tr("Unable to open dictionary file ") + dictFile.fileName() + "/n/n" + dictFile.errorString();    }    // Start searching from the middle    qint64 left = 0;    qint64 right = dictFile.size() - 4096;    dictFile.seek((left + right) / 2);    // 0 = find some matching expression    // 1 = go forward for first matching expr    // 2 = appending text inside matching entry    // 3 = skipping text outside entry    int phase = 0;    QString exprString("<entry key=/"" + expr);    char buf[4096];        QString result;    int numResults = 0;    for(;;)    {        int readRes = dictFile.readLine(&buf[0], 4096);        if(readRes < 0)        {            if(dictFile.atEnd())            {                break;            }            else            {                result += tr("Error reading from dictionary file") + ":/n/n" + dictFile.errorString();            }            break;        }        if(readRes == 0)        {            continue;   // empty line        }        if(phase == 2)        {            QString line(buf);            int entryEnd = line.indexOf("</entry>");            if(entryEnd < 0)            {                result += line;                continue;            }            result += line.left(entryEnd + 8);            numResults++;            if(numResults > maxResults)            {                break;            }            phase = 3;            continue;        }        char *keyStart = strstr(buf, "<entry key=/"");        if(keyStart == 0)        {            continue;        }        keyStart += 12;        char *keyEnd = strchr(keyStart, '"');        QString key = QString::fromUtf8(keyStart, keyEnd - keyStart);        int cmp = compareExprKey(expr, key);        if(cmp == UNCOMPARABLE_CHARS)        {            continue;        // skip uncomparable words        }        if(phase == 0)        {            bool changed = true;            if(cmp > 0)      // expression is bigger then key            {                left = dictFile.pos();            }            else            // expression is smaller or matches            {                changed = (right != dictFile.pos());    // comparing twice same word                right = dictFile.pos();            }            if(changed && (right - left > 4096))            {                dictFile.seek((left + right) / 2);                continue;            }            phase = 1;            dictFile.seek(left);            continue;        }        if(phase == 1)        {            if(cmp > 0)//.........这里部分代码省略.........
开发者ID:radekp,项目名称:qgcide,代码行数:101,


示例15: closingpunct

intclosingpunct(int c){	return strchr(".,:;'/")]}>!?", c) != nil;}
开发者ID:00001,项目名称:plan9port,代码行数:5,


示例16: ps_init

ps_font_info_typeps_init (string font_name, tfm_global_info_type tfm_info){  string base_encoding, mapping;  ps_font_info_type ret;  libfile_start ("postscript", "map");  while ((mapping = libfile_line ()) != NULL         && !STREQ (font_name, strtok (mapping, " /t")))    ;  libfile_close ();  if (mapping == NULL)    {      WARNING2 ("%s: No information for font `%s'; using defaults",                "postscript.map", font_name);      ret.font_name = xstrdup (font_name);      base_encoding = "adobestd";    }  else    { /* We found it; dissect the rest of the line for what we need.         The second word is the full PostScript font name, e.g.,         `Times-BoldItalic'.  The third word is the base filename for         the encoding vector.  */      ret.font_name = strtok (NULL, " /t");      base_encoding = strtok (NULL, " /t");    }  /* Read the encoding file.  We don't store this in the structure we     return, since we've never needed it.  Perhaps we should anyway.  */  encoding = read_encoding_file (base_encoding);  /* The family name would be `Times' for the font `Times-BoldItalic', but it's     `Helvetica' for `Helvetica'.  (It should be `Lucida' for     `LucidaBright-Italic', but we don't handle that case -- maybe     optional arg in mapping file?)  */  ret.family_name = strchr (ret.font_name, '-');  if (ret.family_name == NULL)    ret.family_name = ret.font_name;  /* E.g., `Helvetica'.  */  else    ret.family_name      = substring (ret.font_name, 0, ret.family_name - 1- ret.font_name);  /* If the font name contains `Bold', that's the weight.  Otherwise,     guess `Medium'.  (I don't know of any programs that actually care     about this.  Again, perhaps it should be an optional arg in the     mapping file.)  */  ret.weight = strstr (ret.font_name, "Bold") ? "Bold" : "Medium";  /* We should be able to compute the italic angle by somehow looking at     the characters.  bdftops.ps rotates the `I' and takes the angle     that minimizes the width, for example.  xx */  ret.italic_angle = 0;    /* Monospaced fonts have no stretch or shrink in their interword     space (or shouldn't), but they do have a nonzero interword space     (math fonts sometimes have all their interword space parameters set     to zero).  */  ret.monospace_p    = TFM_FONT_PARAMETER (tfm_info, TFM_STRETCH_PARAMETER) == 0.0      && TFM_FONT_PARAMETER (tfm_info, TFM_SPACE_PARAMETER) != 0.0;  /* What might be a good way to compute this one?  xx */  ret.underline_position = -100;    /* Here we can use the rule thickness from the TFM file, if it's set.     Otherwise, just guess.  (A better guess would be the dominant stem     width in the font.)  */  ret.underline_thickness    = TFM_FONT_PARAMETER (tfm_info, TFM_DEFAULTRULETHICKNESS_PARAMETER)      ? : 50;  /* What to do about the UniqueID's?  Actually, I'm not sure they     should really be necessary.  Adobe wants people to register their     fonts to get a UniqueID from them, which is semi-reasonable, but a     lot of trouble.  We just omit them.  */  ret.unique_id = 0;    /* If there is no version number in the TFM file, then just say it's     version 0.  */  ret.version = TFM_FONT_PARAMETER (tfm_info, TFM_VERSION_PARAMETER)                ? dtoa (TFM_FONT_PARAMETER (tfm_info, TFM_VERSION_PARAMETER))                : "0.0";  return ret;}
开发者ID:apinkney97,项目名称:JSReflow,代码行数:88,


示例17: PE_FindExportedFunction

//.........这里部分代码省略.........    /* Not a fatal problem, some apps do     * GetProcAddress(0,"RegisterPenApp") which triggers this     * case.     */    WARN ("Module %08x(%s)/MODREF %p doesn't have a exports table./n",        wm->module, wm->modname, pem);    return NULL;  }  ordinals = (u_short *) RVA (exports->AddressOfNameOrdinals);  function = (u_long *) RVA (exports->AddressOfFunctions);  name = (u_char **) RVA (exports->AddressOfNames);  rva_start =      PE_HEADER (wm->module)->      OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;  rva_end =      rva_start +      PE_HEADER (wm->module)->      OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size;  //TRACE(".. search in %ld symbols/n",exports->NumberOfNames);  if (HIWORD (funcName)) {    int min = 0, max = exports->NumberOfNames - 1;    while (min <= max) {      int res, pos = (min + max) / 2;      ename = RVA (name[pos]);      if (!(res = strcmp ((char *) ename, funcName))) {        ordinal = ordinals[pos];        goto found;      }      if (res > 0)        max = pos - 1;      else        min = pos + 1;    }    for (i = 0; i < exports->NumberOfNames; i++) {      ename = RVA (name[i]);      if (!strcmp ((char *) ename, funcName)) {        ERR ("%s.%s required a linear search/n", wm->modname, funcName);        ordinal = ordinals[i];        goto found;      }    }    return NULL;  } else {    ordinal = LOWORD (funcName) - exports->Base;    if (snoop && name) {      for (i = 0; i < exports->NumberOfNames; i++)        if (ordinals[i] == ordinal) {          ename = RVA (name[i]);          break;        }    }  }found:  //TRACE("ordinal = %d (of %d)/n", ordinal, exports->NumberOfFunctions);  if (ordinal >= exports->NumberOfFunctions) {    TRACE ("	ordinal %ld out of range!/n", ordinal + exports->Base);    return NULL;  }  addr = function[ordinal];  if (!addr) {    TRACE ("no address for function '%s'/n", funcName);    return NULL;  }  if ((addr < rva_start) || (addr >= rva_end)) {    FARPROC proc = RVA (addr);    if (snoop) {      if (!ename)        ename = (u_char *) "@";      //proc = SNOOP_GetProcAddress(wm->module,ename,ordinal,proc);      //TRACE("SNOOP_GetProcAddress n/a/n");    }    return proc;  } else {    WINE_MODREF *wm;    char *forward = RVA (addr);    char module[256];    char *end = strchr (forward, '.');    TRACE ("getting next module name from '%s'/n", forward);    if (!end)      return NULL;    if (end - forward >= sizeof (module)) {      WARN ("need to enlarge buffer from %d to %ld/n", sizeof (module),          (long) (end - forward));      return NULL;    }    memcpy (module, forward, end - forward);    module[end - forward] = 0;    TRACE ("calling FindModule(%s)/n", module);    if (!(wm = MODULE_FindModule (module))) {      ERR ("module not found for forward '%s'/n", forward);      return NULL;    }    return MODULE_GetProcAddress (wm->module, end + 1, snoop);  }}
开发者ID:Buzztrax,项目名称:buzztrax,代码行数:101,


示例18: miniopt

/* ----------------------------------------------------------------------- */intminiopt(miniopt_t *t, char **argv){	int keylen;	char *p, *eq, *valstr, *endptr = NULL;	int err = 0;	t->consumed = 0;	t->positional = FALSE;	memset(t->key, 0, MINIOPT_MAXKEY);	t->opt = '/0';	t->valstr = NULL;	t->good_int = FALSE;	valstr = NULL;	if (*argv == NULL) {		err = -1;		goto exit;	}	p = *argv++;	t->consumed++;	if (!t->opt_end && !strcmp(p, "--")) {		t->opt_end = TRUE;		if (*argv == NULL) {			err = -1;			goto exit;		}		p = *argv++;		t->consumed++;	}	if (t->opt_end) {		t->positional = TRUE;		valstr = p;	}	else if (!strncmp(p, "--", 2)) {		eq = strchr(p, '=');		if (eq == NULL && !t->longflags) {			fprintf(stderr,				"%s: missing /" = /" in long param /"%s/"/n", t->name, p);			err = 1;			goto exit;		}		keylen = eq ? (eq - (p + 2)) : (int)strlen(p) - 2;		if (keylen > 63) keylen = 63;		memcpy(t->key, p + 2, keylen);		if (eq) {			valstr = eq + 1;			if (*valstr == '/0') {				fprintf(stderr,				        "%s: missing value after /" = /" in long param /"%s/"/n",				        t->name, p);				err = 1;				goto exit;			}		}	}	else if (!strncmp(p, "-", 1)) {		t->opt = p[1];		if (strlen(p) > 2) {			fprintf(stderr,				"%s: only single char options, error on param /"%s/"/n",				t->name, p);			err = 1;			goto exit;		}		if (strchr(t->flags, t->opt)) {			/* this is a flag option, no value expected */			valstr = NULL;		} else {			if (*argv == NULL) {				fprintf(stderr,				"%s: missing value parameter after /"%s/"/n", t->name, p);				err = 1;				goto exit;			}			valstr = *argv;			argv++;			t->consumed++;		}	} else {		t->positional = TRUE;		valstr = p;	}	/* parse valstr as int just in case */	if (valstr) {		t->uval = (uint)strtoul(valstr, &endptr, 0);		t->val = (int)t->uval;		t->good_int = (*endptr == '/0');	}	t->valstr = valstr;exit:	if (err == 1)//.........这里部分代码省略.........
开发者ID:Antares84,项目名称:asuswrt-merlin,代码行数:101,


示例19: run_prompt_command

static enum requestrun_prompt_command(struct view *view, char *cmd){	enum request request;	if (!cmd)		return REQ_NONE;	if (string_isnumber(cmd)) {		int lineno = view->pos.lineno + 1;		if (parse_int(&lineno, cmd, 1, view->lines + 1) == SUCCESS) {			select_view_line(view, lineno - 1);			report_clear();		} else {			report("Unable to parse '%s' as a line number", cmd);		}	} else if (iscommit(cmd)) {		string_ncopy(view->env->search, cmd, strlen(cmd));		request = view_request(view, REQ_JUMP_COMMIT);		if (request == REQ_JUMP_COMMIT) {			report("Jumping to commits is not supported by the '%s' view", view->name);		}	} else if (strlen(cmd) == 1) {		struct key_input input = { { cmd[0] } };		return get_keybinding(&view->ops->keymap, &input);	} else if (cmd[0] == '/' || cmd[0] == '?') {		const char *search = cmd + 1;		if (!strcmp(search, view->env->search))			return cmd[0] == '/' ? REQ_FIND_NEXT : REQ_FIND_PREV;		string_ncopy(view->env->search, search, strlen(search));		return cmd[0] == '/' ? REQ_SEARCH : REQ_SEARCH_BACK;	} else if (cmd[0] == '!') {		struct view *next = VIEW(REQ_VIEW_PAGER);		const char *argv[SIZEOF_ARG];		int argc = 0;		cmd++;		/* When running random commands, initially show the		 * command in the title. However, it maybe later be		 * overwritten if a commit line is selected. */		string_ncopy(next->ref, cmd, strlen(cmd));		if (!argv_from_string(argv, &argc, cmd)) {			report("Too many arguments");		} else if (!argv_format(view->env, &next->argv, argv, FALSE, TRUE)) {			report("Argument formatting failed");		} else {			next->dir = NULL;			open_view(view, REQ_VIEW_PAGER, OPEN_PREPARED);		}	} else {		request = get_request(cmd);		if (request != REQ_UNKNOWN)			return request;		char *args = strchr(cmd, ' ');		if (args) {			*args++ = 0;			if (set_option(cmd, args) == SUCCESS) {				request = !view->unrefreshable ? REQ_REFRESH : REQ_SCREEN_REDRAW;				if (!strcmp(cmd, "color"))					init_colors();				resize_display();				redraw_display(TRUE);			}		}		return request;	}	return REQ_NONE;}
开发者ID:fourks,项目名称:tig,代码行数:79,


示例20: Q_ASSERT

iconv_t QIconvCodec::createIconv_t(const char *to, const char *from){    Q_ASSERT((to == 0 && from != 0) || (to != 0 && from == 0));    iconv_t cd = (iconv_t) -1;#if defined(__GLIBC__) || defined(GNU_LIBICONV)    // both GLIBC and libgnuiconv will use the locale's encoding if from or to is an empty string    static const char empty_codeset[] = "";    const char *codeset = empty_codeset;    cd = iconv_open(to ? to : codeset, from ? from : codeset);#else    char *codeset = 0;#endif#if defined(_XOPEN_UNIX) && !defined(Q_OS_QNX6) && !defined(Q_OS_OSF)    if (cd == (iconv_t) -1) {        codeset = nl_langinfo(CODESET);        if (codeset)            cd = iconv_open(to ? to : codeset, from ? from : codeset);    }#endif    if (cd == (iconv_t) -1) {        // Very poorly defined and followed standards causes lots of        // code to try to get all the cases... This logic is        // duplicated in QTextCodec, so if you change it here, change        // it there too.        // Try to determine locale codeset from locale name assigned to        // LC_CTYPE category.        // First part is getting that locale name.  First try setlocale() which        // definitely knows it, but since we cannot fully trust it, get ready        // to fall back to environment variables.        char * ctype = qstrdup(setlocale(LC_CTYPE, 0));        // Get the first nonempty value from $LC_ALL, $LC_CTYPE, and $LANG        // environment variables.        char * lang = qstrdup(qgetenv("LC_ALL").constData());        if (!lang || lang[0] == 0 || strcmp(lang, "C") == 0) {            if (lang) delete [] lang;            lang = qstrdup(qgetenv("LC_CTYPE").constData());        }        if (!lang || lang[0] == 0 || strcmp(lang, "C") == 0) {            if (lang) delete [] lang;            lang = qstrdup(qgetenv("LANG").constData());        }        // Now try these in order:        // 1. CODESET from ctype if it contains a .CODESET part (e.g. en_US.ISO8859-15)        // 2. CODESET from lang if it contains a .CODESET part        // 3. ctype (maybe the locale is named "ISO-8859-1" or something)        // 4. locale (ditto)        // 5. check for "@euro"        // 1. CODESET from ctype if it contains a .CODESET part (e.g. en_US.ISO8859-15)        codeset = ctype ? strchr(ctype, '.') : 0;        if (codeset && *codeset == '.') {            ++codeset;            cd = iconv_open(to ? to : codeset, from ? from : codeset);        }        // 2. CODESET from lang if it contains a .CODESET part        codeset = lang ? strchr(lang, '.') : 0;        if (cd == (iconv_t) -1 && codeset && *codeset == '.') {            ++codeset;            cd = iconv_open(to ? to : codeset, from ? from : codeset);        }        // 3. ctype (maybe the locale is named "ISO-8859-1" or something)        if (cd == (iconv_t) -1 && ctype && *ctype != 0 && strcmp (ctype, "C") != 0)            cd = iconv_open(to ? to : ctype, from ? from : ctype);        // 4. locale (ditto)        if (cd == (iconv_t) -1 && lang && *lang != 0)            cd = iconv_open(to ? to : lang, from ? from : lang);        // 5. "@euro"        if ((cd == (iconv_t) -1 && ctype && strstr(ctype, "@euro")) || (lang && strstr(lang, "@euro")))            cd = iconv_open(to ? to : "ISO8859-15", from ? from : "ISO8859-15");        delete [] ctype;        delete [] lang;    }    return cd;}
开发者ID:Fale,项目名称:qtmoko,代码行数:88,


示例21: read_cmdline

/// Parse command line.  Clobbers localbuf.static bool read_cmdline(int argc, char *argv[]){  assert(argv[argc-1]);  assert(!argv[argc]);  for (int i=1; i<argc; ++i)  {    assert(argv[i]);    const char *nextarg = NULL;    if (argv[i][0] != '-' || !argv[i][1])    {      fprintf(stderr, "Illegal argument: %s/n", argv[i]);      return false;    }    const char o = argv[i][1];    const char *optname;    if (o == '-')    {      // Long option name (starting with double dash)      optname = argv[i]+2;      if (!optname[0] || !isalpha(optname[0]))      {	fprintf(stderr, "Illegal argument: %s/n", argv[i]);	return false;      }      const char *const eqsign = strchr(optname, '=');      if (eqsign)      {	// Option in '--foo=bar' style	const size_t optnamelen = eqsign - optname;	if (optnamelen >= sizeof(localbuf))	{	  fprintf(stderr, "Option name too long/n");	  return false;	}	strncpy(localbuf, optname, optnamelen);	localbuf[optnamelen] = '/0';	optname = localbuf;	nextarg = eqsign + 1;      }    }    else    {      // Short option name (starting with single dash)      int j;      for (j=0;	   j<sizeof(options)/sizeof(*options) && options[j].shortopt != o;	   ++j);      if (j == sizeof(options)/sizeof(*options))      {	fprintf(stderr, "Illegal option: -%c/n", o);	return false;      }      optname = options[j].name;      if (argv[i][2]) nextarg = argv[i] + 2;    }    if (!nextarg && argv[i+1] && (argv[i+1][0]!='-'||isdigit(argv[i+1][1])))    {      ++i;      nextarg = argv[i];    }    if (!handle_configitem(optname, nextarg)) return false;  }  return true;}
开发者ID:briangough,项目名称:Swapspace,代码行数:69,


示例22: gprintf

//.........这里部分代码省略.........		    }		} else {			mant_exp(log10_of_1024, x, FALSE, NULL, &power, "%.0f");		}		if (power > 0 && power <= 8) {		    /* name  power		       -----------		       Yobi   8		       Zebi   7		       Exbi   9		       Pebi   5		       Tebi   4		       Gibi   3		       Mebi   2		       kibi   1   */		    snprintf(dest, remaining_space, temp, " kMGTPEZY"[power]);		} else if (power > 8) {		    /* for the larger values, print x2^{10}Gi for example */		    snprintf(dest, remaining_space, "x2^{%d}Yi", power-8);		} else if (power < 0) {		    snprintf(dest, remaining_space, "x2^{%d}", power*10);		} else {                    snprintf(dest, remaining_space, "  ");                }		break;	    }	    /*}}} */	    /*{{{  P --- multiple of pi */	case 'P':	    {		t[0] = 'f';		t[1] = 0;		snprintf(dest, remaining_space, temp, x / M_PI);		break;	    }	    /*}}} */	default:	   reset_numeric_locale();	   int_error(NO_CARET, "Bad format character");	} /* switch */	/*}}} */	if (got_hash && (format != strpbrk(format,"oeEfFgG"))) {	   reset_numeric_locale();	   int_error(NO_CARET, "Bad format character");	}    /* change decimal '.' to the actual entry in decimalsign */	if (decimalsign != NULL) {	    char *dotpos1 = dest;	    char *dotpos2;	    size_t newlength = strlen(decimalsign);	    /* dot is the default decimalsign we will be replacing */	    int dot = *get_decimal_locale();	    /* replace every dot by the contents of decimalsign */	    while ((dotpos2 = strchr(dotpos1,dot)) != NULL) {		if (newlength == 1) {	/* The normal case */		    *dotpos2 = *decimalsign;		    dotpos1++;		} else {		/* Some multi-byte decimal marker */		    size_t taillength = strlen(dotpos2);		    dotpos1 = dotpos2 + newlength;		    if (dotpos1 + taillength > limit)			int_error(NO_CARET,				  "format too long due to decimalsign string");		    /* move tail end of string out of the way */		    memmove(dotpos1, dotpos2 + 1, taillength);		    /* insert decimalsign */		    memcpy(dotpos2, decimalsign, newlength);		}	    }	}	/* this was at the end of every single case, before: */	dest += strlen(dest);	++format;    } /* for ever */done:#if (0)    /* Oct 2013 - Not safe because it fails to recognize LaTeX macros.	*/    /* For LaTeX terminals, if the user has not already provided a   	*/    /* format in math mode, wrap whatever we got by default in $...$ 	*/    if (((term->flags & TERM_IS_LATEX)) && !strchr(tempdest, '$')) {	*(outstring++) = '$';	strcat(tempdest, "$");	count -= 2;    }#endif    /* Copy as much as fits */    safe_strncpy(outstring, tempdest, count);    reset_numeric_locale();}
开发者ID:asherliu,项目名称:gnuplot,代码行数:101,


示例23: list_modules

void list_modules(){	DIR* dir = NULL;	struct dirent *dp = NULL;	char *moddir  = NULL;	moddir = get_module_dir();	if(moddir == NULL)	{		error("Failure getting module directory! (Perhaps set MPG123_MODDIR?)");		exit(-1); /* TODO: change this to return a value instead of exit()! */	}	/* Open the module directory */	dir = opendir(moddir);	if (dir==NULL) {		error2("Failed to open the module directory (%s): %s/n", PKGLIBDIR, strerror(errno));		free(moddir);		exit(-1);	}		if(chdir(moddir) != 0)	{		error2("Failed to enter module directory (%s): %s/n", PKGLIBDIR, strerror(errno));		closedir( dir );		free(moddir);		exit(-1);	}	/* Display the program title */	/* print_title(stderr); */	/* List the output modules */	printf("/n");	printf("Available modules/n");	printf("-----------------/n");		while( (dp = readdir(dir)) != NULL ) {		struct stat fst;		if(stat(dp->d_name, &fst) != 0) continue;		if(S_ISREG(fst.st_mode)) /* Allow links? */		{			char* ext = dp->d_name + strlen( dp->d_name ) - strlen( MODULE_FILE_SUFFIX );			if (strcmp(ext, MODULE_FILE_SUFFIX) == 0)			{				char *module_name = NULL;				char *module_type = NULL;				char *uscore_pos = NULL;				mpg123_module_t *module = NULL;								/* Extract the module type */				module_type = strdup( dp->d_name );				uscore_pos = strchr( module_type, '_' );				if (uscore_pos==NULL || (uscore_pos>=module_type+strlen(module_type)+1) )				{					free(module_type);					continue;				}								*uscore_pos = '/0';								/* Extract the short name of the module */				module_name = strdup( dp->d_name + strlen( module_type ) + 1 );				module_name[ strlen( module_name ) - strlen( MODULE_FILE_SUFFIX ) ] = '/0';				/* Open the module */				module = open_module_here(module_type, module_name);				if (module) {					printf("%-15s%s  %s/n", module->name, module_type, module->description );									/* Close the module again */					close_module( module );				}				free( module_name );				free( module_type );			}		}	}	closedir( dir );	free(moddir);	exit(0);}
开发者ID:JoeyZheng,项目名称:deadbeef,代码行数:80,


示例24: cpio_getopt

/* * I used to try to select platform-provided getopt() or * getopt_long(), but that caused a lot of headaches.  In particular, * I couldn't consistently use long options in the test harness * because not all platforms have getopt_long().  That in turn led to * overuse of the -W hack in the test harness, which made it rough to * run the test harness against GNU cpio.  (I periodically run the * test harness here against GNU cpio as a sanity-check.  Yes, * I've found a couple of bugs in GNU cpio that way.) */intcpio_getopt(struct cpio *cpio){	enum { state_start = 0, state_next_word, state_short, state_long };	static int state = state_start;	static char *opt_word;	const struct option *popt, *match = NULL, *match2 = NULL;	const char *p, *long_prefix = "--";	size_t optlength;	int opt = '?';	int required = 0;	cpio->argument = NULL;	/* First time through, initialize everything. */	if (state == state_start) {		/* Skip program name. */		++cpio->argv;		--cpio->argc;		state = state_next_word;	}	/*	 * We're ready to look at the next word in argv.	 */	if (state == state_next_word) {		/* No more arguments, so no more options. */		if (cpio->argv[0] == NULL)			return (-1);		/* Doesn't start with '-', so no more options. */		if (cpio->argv[0][0] != '-')			return (-1);		/* "--" marks end of options; consume it and return. */		if (strcmp(cpio->argv[0], "--") == 0) {			++cpio->argv;			--cpio->argc;			return (-1);		}		/* Get next word for parsing. */		opt_word = *cpio->argv++;		--cpio->argc;		if (opt_word[1] == '-') {			/* Set up long option parser. */			state = state_long;			opt_word += 2; /* Skip leading '--' */		} else {			/* Set up short option parser. */			state = state_short;			++opt_word;  /* Skip leading '-' */		}	}	/*	 * We're parsing a group of POSIX-style single-character options.	 */	if (state == state_short) {		/* Peel next option off of a group of short options. */		opt = *opt_word++;		if (opt == '/0') {			/* End of this group; recurse to get next option. */			state = state_next_word;			return cpio_getopt(cpio);		}		/* Does this option take an argument? */		p = strchr(short_options, opt);		if (p == NULL)			return ('?');		if (p[1] == ':')			required = 1;		/* If it takes an argument, parse that. */		if (required) {			/* If arg is run-in, opt_word already points to it. */			if (opt_word[0] == '/0') {				/* Otherwise, pick up the next word. */				opt_word = *cpio->argv;				if (opt_word == NULL) {					lafe_warnc(0,					    "Option -%c requires an argument",					    opt);					return ('?');				}				++cpio->argv;				--cpio->argc;			}			if (opt == 'W') {				state = state_long;				long_prefix = "-W "; /* For clearer errors. *///.........这里部分代码省略.........
开发者ID:SylvainGarrigues,项目名称:freebsd,代码行数:101,


示例25: variable_expand_string

/* Scan STRING for variable references and expansion-function calls.  Only   LENGTH bytes of STRING are actually scanned.  If LENGTH is -1, scan until   a null byte is found.   Write the results to LINE, which must point into 'variable_buffer'.  If   LINE is NULL, start at the beginning of the buffer.   Return a pointer to LINE, or to the beginning of the buffer if LINE is   NULL. */char *variable_expand_string (char *line, const char *string, long length){  struct variable *v;  const char *p, *p1;  char *save;  char *o;  unsigned int line_offset;  if (!line)    line = initialize_variable_output();  o = line;  line_offset = line - variable_buffer;  if (length == 0)    {      variable_buffer_output (o, "", 1);      return (variable_buffer);    }  /* We need a copy of STRING: due to eval, it's possible that it will get     freed as we process it (it might be the value of a variable that's reset     for example).  Also having a nil-terminated string is handy.  */  save = length < 0 ? xstrdup (string) : xstrndup (string, length);  p = save;  while (1)    {      /* Copy all following uninteresting chars all at once to the         variable output buffer, and skip them.  Uninteresting chars end	 at the next $ or the end of the input.  */      p1 = strchr (p, '$');      o = variable_buffer_output (o, p, p1 != 0 ? (unsigned int)(p1 - p) : strlen (p) + 1);      if (p1 == 0)	break;      p = p1 + 1;      /* Dispatch on the char that follows the $.  */      switch (*p)	{	case '$':	  /* $$ seen means output one $ to the variable output buffer.  */	  o = variable_buffer_output (o, p, 1);	  break;	case '(':	case '{':	  /* $(...) or ${...} is the general case of substitution.  */	  {	    char openparen = *p;	    char closeparen = (openparen == '(') ? ')' : '}';            const char *begp;	    const char *beg = p + 1;	    char *op;            char *abeg = NULL;	    const char *end, *colon;	    op = o;	    begp = p;	    if (handle_function (&op, &begp))	      {		o = op;		p = begp;		break;	      }	    /* Is there a variable reference inside the parens or braces?	       If so, expand it before expanding the entire reference.  */	    end = strchr (beg, closeparen);	    if (end == 0)              /* Unterminated variable reference.  */              fatal (*expanding_var, _("unterminated variable reference"));	    p1 = lindex (beg, end, '$');	    if (p1 != 0)	      {		/* BEG now points past the opening paren or brace.		   Count parens or braces until it is matched.  */		int count = 0;		for (p = beg; *p != '/0'; ++p)		  {		    if (*p == openparen)		      ++count;		    else if (*p == closeparen && --count < 0)		      break;		  }		/* If COUNT is >= 0, there were unmatched opening parens//.........这里部分代码省略.........
开发者ID:ndmitchell,项目名称:gnumake,代码行数:101,


示例26: mgmt_get_main_config

/* * mgmt_get_main_config() loads main configuration * from scf into a node tree. * Main configuration includes: admin/target/tpgt/initiator info. * admin info is stored in "iscsitgt" property group * target info is stored in "target_<name>" property group * initiator info is stored in "initiator_<name>" property group * tpgt info is stored in "tpgt_<number>" property group */Boolean_tmgmt_get_main_config(tgt_node_t **node){	targ_scf_t *h = NULL;	scf_property_t *prop = NULL;	scf_value_t *value = NULL;	scf_iter_t *iter = NULL;	scf_iter_t *iter_v = NULL;	scf_iter_t *iter_pv = NULL;	char *pname = NULL;	char *valuebuf = NULL;	ssize_t max_name_len;	ssize_t max_value_len;	char passcode[32];	unsigned int outlen;	tgt_node_t	*n;	tgt_node_t	*pn;	tgt_node_t	*vn;	Boolean_t	status = False;	h = mgmt_handle_init();	if (h == NULL)		return (status);	prop = scf_property_create(h->t_handle);	value = scf_value_create(h->t_handle);	iter = scf_iter_create(h->t_handle);	if ((alloc_scf_name(&max_name_len, (void *)&pname) == False) ||	    (alloc_scf_value(&max_value_len, (void *)&valuebuf) == False)) {		goto error;	}	(void) pthread_mutex_lock(&scf_conf_mutex);	/* Basic Information is stored in iscsitgt pg */	if (scf_service_get_pg(h->t_service, "iscsitgt", h->t_pg) == -1) {		goto error;	}	*node = NULL;	*node = tgt_node_alloc("main_config", String, NULL);	if (*node == NULL)		goto error;	if (scf_iter_pg_properties(iter, h->t_pg) == -1) {		goto error;	}	while (scf_iter_next_property(iter, prop) > 0) {		(void) scf_property_get_value(prop, value);		(void) scf_value_get_as_string(value, valuebuf, max_value_len);		(void) scf_property_get_name(prop, pname, max_name_len);		/* avoid load auth to incore data */		if (strcmp(pname, ISCSI_READ_AUTHNAME) == 0 ||		    strcmp(pname, ISCSI_MODIFY_AUTHNAME) == 0 ||		    strcmp(pname, ISCSI_VALUE_AUTHNAME) == 0)			continue;		n = tgt_node_alloc(pname, String, valuebuf);		if (n == NULL)			goto error;		/* put version info into root node's attr */		if (strcmp(pname, XML_ELEMENT_VERS) == 0) {			tgt_node_add_attr(*node, n);		} else {		/* add other basic info into root node */			tgt_node_add(*node, n);		}	}	/*	 * targets/initiators/tpgt information is	 * stored as type "configuration" in scf	 * each target's param is stored as type "parameter"	 */	if (scf_iter_service_pgs_typed(iter, h->t_service, "configuration")	    == -1) {		goto error;	}	while (scf_iter_next_pg(iter, h->t_pg) > 0) {		char *iname;		(void) scf_pg_get_name(h->t_pg, pname, max_name_len);		pgname_decode(pname);		iname = strchr(pname, '_');		if (iname == NULL) {//.........这里部分代码省略.........
开发者ID:imp,项目名称:slist,代码行数:101,



注:本文中的strchr函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


C++ strchrnul函数代码示例
C++ strcat_s函数代码示例
万事OK自学网:51自学网_软件自学网_CAD自学网自学excel、自学PS、自学CAD、自学C语言、自学css3实例,是一个通过网络自主学习工作技能的自学平台,网友喜欢的软件自学网站。