这篇教程C++ sscanf函数代码示例写得很实用,希望能帮到您。
本文整理汇总了C++中sscanf函数的典型用法代码示例。如果您正苦于以下问题:C++ sscanf函数的具体用法?C++ sscanf怎么用?C++ sscanf使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。 在下文中一共展示了sscanf函数的29个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。 示例1: finbool NoximGlobalTrafficTable::load(const char *fname){ // Open file ifstream fin(fname, ios::in); if (!fin) return false; // Initialize variables traffic_table.clear(); // Cycle reading file while (!fin.eof()) { char line[512]; fin.getline(line, sizeof(line) - 1); if (line[0] != '/0') { if (line[0] != '%') { int src, dst; // Mandatory float pir, por; int t_on, t_off, t_period; int t_use_lvp; int params = sscanf(line, "%d %d %d %f %f %d %d %d", &src, &dst, &t_use_lvp, &pir, &por, &t_on, &t_off, &t_period); if (params >= 2) { // Create a communication from the parameters read on the line NoximCommunication communication; // Mandatory fields communication.src = src; communication.dst = dst; // Use low voltage path if (params >= 3 && t_use_lvp == 1) communication.use_low_voltage_path = true; else communication.use_low_voltage_path = false; // Custom PIR if (params >= 4 && pir >= 0 && pir <= 1) communication.pir = pir; else communication.pir = NoximGlobalParams::packet_injection_rate; // Custom POR if (params >= 5 && por >= 0 && por <= 1) communication.por = por; else communication.por = communication.pir; // NoximGlobalParams::probability_of_retransmission; // Custom Ton if (params >= 6 && t_on >= 0) communication.t_on = t_on; else communication.t_on = 0; // Custom Toff if (params >= 7 && t_off >= 0) { assert(t_off > t_on); communication.t_off = t_off; } else communication.t_off = DEFAULT_RESET_TIME + NoximGlobalParams::simulation_time; // Custom Tperiod if (params >= 8 && t_period > 0) { assert(t_period > t_off); communication.t_period = t_period; } else communication.t_period = DEFAULT_RESET_TIME + NoximGlobalParams::simulation_time; // Add this communication to the vector of communications traffic_table.push_back(communication); } } } } return true;}
开发者ID:Fzzb,项目名称:ExpandableNoxim,代码行数:85,
示例2: init_from_conf_filestatic voidinit_from_conf_file(){ FILE *conf_file; char *line = NULL; #define LINEBUFLEN 256 char var[LINEBUFLEN]; char val[LINEBUFLEN]; size_t len = 0; ssize_t numread; int assigns; char default_icon_path[] = {"/rom/etc/icon.ico"};#ifdef RTCONFIG_RALINK char default_wl_interface[] = {"ra0"};#else char default_wl_interface[] = {"eth1"};#endif /* Set default values for configuration options */ /* (avoid strdup() since it doesn't use xmalloc wrapper) */ g_icon_path = xmalloc(strlen(default_icon_path)+1); strcpy(g_icon_path,default_icon_path); /* Examine configuration file, if it exists */ conf_file = fopen("/rom/etc/lld2d.conf", "r"); if (conf_file == NULL) return; while ((numread = getline(&line, &len, conf_file)) != -1) { var[0] = val[0] = '/0'; assigns = sscanf(line, "%s = %s", var, val); if (assigns==2) { /* compare to each of the 2 allowed vars... */ if (!strcmp(var,"icon")) { char *path = NULL; char *cur = NULL; path = xmalloc(strlen(val)+6); // always allow enough room for a possible prefix of '/etc/' cur = path; /* Check for leading '/' and prefix '/etc/' if missing */ if (val[0] != '/') { strcpy(cur,"/etc/"); cur += 5; } strncpy(cur,val,strlen(val)); if (g_icon_path) xfree(g_icon_path); // always use the most recent occurrence g_icon_path = path; DEBUG({printf("configvar 'g_icon_path' = %s/n", g_icon_path);}) } else if (!strcmp(var,"jumbo-icon")) { char *path = NULL; char *cur = NULL; path = xmalloc(strlen(val)+6); // always allow enough room for a possible prefix of '/etc/' cur = path; /* Check for leading '/' and prefix '/etc/' if missing */ if (val[0] != '/') { strcpy(cur,"/etc/"); cur += 5; } strncpy(cur,val,strlen(val)); if (g_jumbo_icon_path) xfree(g_jumbo_icon_path); // always use the most recent occurrence g_jumbo_icon_path = path; DEBUG({printf("configvar 'g_jumbo_icon_path' = %s/n", g_jumbo_icon_path);}) } else if (!strcmp(var, "wl-interface")) { /* patch here for wireless interface config file, bobtseng 2007.9.7. */
开发者ID:gygy,项目名称:asuswrt,代码行数:69,
示例3: network_connectnetwork_connect(struct scpi_instrument *scpi){ struct sockaddr_in MyAddress, MyControlAddress; int status; struct timeval timeout; char buf[128]; timeout.tv_sec = SOCKETS_TIMEOUT; timeout.tv_usec = 0; /* Create socket (allocate resources) - IPv4, TCP */ scpi->main_socket = socket(PF_INET, SOCK_STREAM, 0); if (scpi->main_socket == -1) { printf("Error: Unable to create socket (%i).../n",errno); return -1; } /* set Recieve and Transmit Timeout, so connect doesn't take so long to fail */ status = setsockopt(scpi->main_socket, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(timeout)); if (status < 0) perror("setsockopt failed/n"); status = setsockopt(scpi->main_socket, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout,sizeof(timeout)); if (status < 0) perror("setsockopt failed/n"); /* Establish TCP connection */ memset(&MyAddress,0,sizeof(struct sockaddr_in)); MyAddress.sin_family = PF_INET; MyAddress.sin_port = htons(scpi->main_port); MyAddress.sin_addr.s_addr = inet_addr(scpi->ip_address); status = connect(scpi->main_socket, (struct sockaddr *)&MyAddress, sizeof(struct sockaddr_in)); if(status == -1) { printf("Error: Unable to establish connection to ip:%s (%i).../n", scpi->ip_address, errno); return -1; } /* Minimize latency by setting TCP_NODELAY option */ network_setnodelay(scpi->main_socket); /* Ask for control port */ sprintf(buf, "SYST:COMM:TCPIP:CONTROL?/n"); status = send(scpi->main_socket, buf, strlen(buf), 0); if (status == -1) return -1; if (scpi_network_read((scpi)) == 0) { scpi->control_socket = scpi->main_socket; return 0; } sscanf(scpi->response, "%" SCNd16, &scpi->control_port); /* Create socket for control port */ scpi->control_socket = socket(PF_INET, SOCK_STREAM, 0); if(scpi->control_socket == -1) { printf("Error: Unable to create control port socket (%i).../n",errno); return -1; } /* Establish TCP connection to control port */ memset(&MyControlAddress, 0, sizeof(struct sockaddr_in)); MyControlAddress.sin_family = PF_INET; MyControlAddress.sin_port = htons(scpi->control_port); MyControlAddress.sin_addr.s_addr = inet_addr(scpi->ip_address); status = connect(scpi->control_socket, (struct sockaddr *) &MyControlAddress, sizeof(struct sockaddr_in)); if(status == -1) { printf("Error: Unable to establish connection to control port (%i).../n", errno); return -1; } return 0;}
开发者ID:dirkcgrunwald,项目名称:iio-oscilloscope,代码行数:78,
示例4: node_handler_fetch_data/** * Process counter data and dispatch values */static int node_handler_fetch_data(void *arg, const char *val, const char *key){ value_t uv; double tmp_d; uint64_t tmp_u; struct values_tmp *vtmp = (struct values_tmp*) arg; uint32_t type = DSET_TYPE_UNFOUND; int index = vtmp->index; char ds_name[DATA_MAX_NAME_LEN]; memset(ds_name, 0, sizeof(ds_name)); if(parse_keys(key, ds_name)) { return 1; } if(index >= vtmp->d->ds_num) { //don't overflow bounds of array index = (vtmp->d->ds_num - 1); } /** * counters should remain in same order we parsed schema... we maintain the * index variable to keep track of current point in list of counters. first * use index to guess point in array for retrieving type. if that doesn't * work, use the old way to get the counter type */ if(strcmp(ds_name, vtmp->d->ds_names[index]) == 0) { //found match type = vtmp->d->ds_types[index]; } else if((index > 0) && (strcmp(ds_name, vtmp->d->ds_names[index-1]) == 0)) { //try previous key type = vtmp->d->ds_types[index-1]; } if(type == DSET_TYPE_UNFOUND) { //couldn't find right type by guessing, check the old way type = backup_search_for_type(vtmp->d, ds_name); } switch(type) { case DSET_LATENCY: if(vtmp->avgcount_exists == -1) { sscanf(val, "%" PRIu64, &vtmp->avgcount); vtmp->avgcount_exists = 0; //return after saving avgcount - don't dispatch value //until latency calculation return 0; } else { double sum, result; sscanf(val, "%lf", &sum); if(vtmp->avgcount == 0) { vtmp->avgcount = 1; } /** User wants latency values as long run avg */ if(long_run_latency_avg) { result = (sum / vtmp->avgcount); } else { result = get_last_avg(vtmp->d, ds_name, vtmp->latency_index, sum, vtmp->avgcount); if(result == -ENOMEM) { return -ENOMEM; } } uv.gauge = result; vtmp->avgcount_exists = -1; vtmp->latency_index = (vtmp->latency_index + 1); } break; case DSET_BYTES: sscanf(val, "%lf", &tmp_d); uv.gauge = tmp_d; break; case DSET_RATE: sscanf(val, "%" PRIu64, &tmp_u); uv.derive = tmp_u; break; case DSET_TYPE_UNFOUND: default: ERROR("ceph plugin: ds %s was not properly initialized.", ds_name);//.........这里部分代码省略.........
开发者ID:QualityUnit,项目名称:collectd,代码行数:101,
示例5: nand_test_store/******************************************************************************Name :*Description :receive testcase num from echo command*Parameter :*Return :*Note :*****************************************************************************/static ssize_t nand_test_store(struct kobject *kobject,struct attribute *attr, const char *buf, size_t count){ int ret; int argnum = 0; char cmd[32] = {0}; unsigned int param0 = 0; unsigned int param1 = 0; unsigned int param2 = 0; struct nand_kobject* nand_kobj; nand_kobj = (struct nand_kobject*)kobject; argnum = sscanf(buf, "%s %u %u %u ", cmd, ¶m0, ¶m1, ¶m2); printk("argnum=%i, cmd=%s, param0=%u, param1=%u, param2=%u/n", argnum, cmd, param0, param1, param2); if (-1 == argnum) { printk("cmd format err!"); goto NAND_TEST_STORE_EXIT; } if(strcmp(cmd,"help") == 0) { printk("nand debug cmd:/n"); printk(" help /n"); } else if(strcmp(cmd,"flush") == 0) { printk("nand debug cmd:/n"); printk(" flush /n"); mutex_lock(nand_kobj->nftl_blk->blk_lock); ret = nand_kobj->nftl_blk->flush_write_cache(nand_kobj->nftl_blk,param0); mutex_unlock(nand_kobj->nftl_blk->blk_lock); goto NAND_TEST_STORE_EXIT; } else if(strcmp(cmd,"gcall") == 0) { printk("nand debug cmd:/n"); printk(" gcall /n"); mutex_lock(nand_kobj->nftl_blk->blk_lock); ret = gc_all(nand_kobj->nftl_blk->nftl_zone); mutex_unlock(nand_kobj->nftl_blk->blk_lock); goto NAND_TEST_STORE_EXIT; } else if(strcmp(cmd,"gcone") == 0) { printk("nand debug cmd:/n"); printk(" gcone /n"); mutex_lock(nand_kobj->nftl_blk->blk_lock); ret = gc_one(nand_kobj->nftl_blk->nftl_zone); mutex_unlock(nand_kobj->nftl_blk->blk_lock); goto NAND_TEST_STORE_EXIT; } else if(strcmp(cmd,"test") == 0) { printk("nand debug cmd:/n"); printk(" test /n"); mutex_lock(nand_kobj->nftl_blk->blk_lock); ret = nftl_set_zone_test((void*)nand_kobj->nftl_blk->nftl_zone,param0); mutex_unlock(nand_kobj->nftl_blk->blk_lock); goto NAND_TEST_STORE_EXIT; } else if(strcmp(cmd,"showall") == 0) { printk("nand debug cmd:/n"); printk(" show all /n"); print_free_list(nand_kobj->nftl_blk->nftl_zone); print_block_invalid_list(nand_kobj->nftl_blk->nftl_zone); print_nftl_zone(nand_kobj->nftl_blk->nftl_zone); goto NAND_TEST_STORE_EXIT; } else { printk("err, nand debug undefined cmd: %s/n", cmd); }NAND_TEST_STORE_EXIT: return count;}
开发者ID:GREYFOXRGR,项目名称:BPI-M3-bsp,代码行数:86,
示例6: mainint main(int argc, char *argv[]){ int k, i, j, x, y; int A[5][5]; seq seq1 = {o, a, a, a, b, a}; seq seq2 = {o, b, a, a, b, a}; if(argc != 2 || (sscanf(argv[1], "%d", &k)) != 1) { printf("/tBitte Syntax beachten: ./afg41 <Substringlaenge>/n"); exit(EXIT_FAILURE); } printf("/n"); for(i = 1; i <= 6 - k; i++){ for(j = 1; j <= 6 - k; j++){ printf("/tmc("); for(x = k; x > 0; x--) { printf("%c", seq1[i+(k-x)]); if(x == 1) { printf(", "); } } for(y = k; y > 0; y--) { printf("%c", seq2[j+(k-y)]); if(y == 1) { printf(")/n"); } } } } for(j = 0; j < 6; j++) { printf("/n"); for(i = 0; i < 6; i++) { if((i == 0) || (j == 0)) { A[i][j] = 0; } else { A[i][j] = A[i-1][j-1]; if(seq1[i] == seq2[j]) { A[i][j] += 1; } } printf("/t%d", A[i][j]); } } printf("/n/n"); for(i = 1; i <= 6 - k; i++){ for(j = 1; j <= 6 - k; j++){ printf("/tmc("); for(x = k; x > 0; x--) { printf("%c", seq1[i+(k-x)]); if(x == 1) { printf(", "); } } for(y = k; y > 0; y--) { printf("%c", seq2[j+(k-y)]); if(y == 1) { printf(") = %d/n", (A[i+(k-1)][j+(k-1)] - A[i-1][j-1])); } } } } printf("/n"); return(EXIT_SUCCESS);}
开发者ID:AlexWoroschilow,项目名称:uni,代码行数:68,
示例7: process_inputvoid process_input(int* needs_refresh, const char *str, int fd, void (*cb)(int fd, const char *data, size_t len)){ static unsigned lcore_id, task_id, nb_packets, val, id, port, queue, rate, ip[4], prefix, next_hop_idx, interface, gre_id, svlan, cvlan, mac[6], user; unsigned count; float speed; uint32_t pkt_size; static char mode[20]; struct rte_ring *ring; unsigned short offset; uint32_t value; uint8_t value_len; if (strcmp(str, "quit") == 0) { plog_info("Leaving.../n"); stop_core_all(); stop_dppd = 1; } else if (sscanf(str, "dump %u %u %u", &lcore_id, &task_id, &nb_packets) == 3) { if (lcore_id >= RTE_MAX_LCORE) { plog_err("Invalid core id %u (lcore ID above %d)/n", lcore_id, RTE_MAX_LCORE); } else if (!dppd_core_active(lcore_id, 0)) { plog_err("Invalid core id %u (lcore is not active)/n", lcore_id); } else { cmd_dump(lcore_id, task_id, nb_packets); } } else if (sscanf(str, "rate %u %u %u", &queue, &port, &rate) == 3) { if (port > DPPD_MAX_PORTS) { plog_err("Max port id allowed is %u (specified %u)/n", DPPD_MAX_PORTS, port); } else if (!dppd_port_cfg[port].active) { plog_err("Port %u not active/n", port); } else if (queue >= dppd_port_cfg[port].n_txq) { plog_err("Number of active queues is %u/n", dppd_port_cfg[port].n_txq); } else if (rate > dppd_port_cfg[port].link_speed) { plog_err("Max rate allowed on port %u queue %u is %u Mbps/n", port, queue, dppd_port_cfg[port].link_speed); } else { if (rate == 0) { plog_info("Disabling rate limiting on port %u queue %u/n", port, queue); } else { plog_info("Setting rate limiting to %u Mbps on port %u queue %u/n", rate, port, queue); } rte_eth_set_queue_rate_limit(port, queue, rate); } } else if (sscanf(str, "count %u %u %u", &lcore_id, &task_id, &count) == 3) { if (check_core_task(lcore_id, task_id)) { if (strcmp(lcore_cfg[lcore_id].targs[task_id].task_init->mode_str, "gen")) { plog_err("Core %u task %u is not generating packets/n", lcore_id, task_id); } else { ((struct task_gen *)lcore_cfg[lcore_id].task[task_id])->pkt_count = count; plog_info("Core %u task %u stopping after %u packets/n", lcore_id, task_id, count); } } } else if (sscanf(str, "pkt_size %u %u %d", &lcore_id, &task_id, &pkt_size) == 3) { if (check_core_task(lcore_id, task_id)) { if (strcmp(lcore_cfg[lcore_id].targs[task_id].task_init->mode_str, "gen")) { plog_err("Core %u task %u is not generating packets/n", lcore_id, task_id); } else if (pkt_size > 1514 || pkt_size < 34) { // 34 for 14 + 20 (MAC, EtherType and IP) plog_err("pkt_size out of range (must be betweeen 34 and 1514)/n"); } else { ((struct task_gen *)lcore_cfg[lcore_id].task[task_id])->pkt_size = pkt_size; plog_info("Setting pkt_size to %u /n", pkt_size); } } } else if (sscanf(str, "speed %u %u %f", &lcore_id, &task_id, &speed) == 3) { if (check_core_task(lcore_id, task_id)) { if (strcmp(lcore_cfg[lcore_id].targs[task_id].task_init->mode_str, "gen")) { plog_err("Core %u task %u is not generating packets/n", lcore_id, task_id); } else if (speed > 100.0f || speed < 0.0f) { plog_err("Speed out of range (must be betweeen 0%% and 100%%)/n"); } else { uint64_t bps = speed * 12500000; ((struct task_gen *)lcore_cfg[lcore_id].task[task_id])->rate_bps = bps; plog_info("Setting rate to %"PRIu64" Bps/n", bps); } } } else if (sscanf(str, "speed_byte %u %u %u", &lcore_id, &task_id, &value) == 3) {//.........这里部分代码省略.........
开发者ID:gonzopancho,项目名称:dppd-BNG,代码行数:101,
示例8: gl/** Get a value (object, clock, or global) /verbatim gl('get',name) /endverbatim **/void cmex_get(int nlhs, mxArray *plhs[], /**< {data} */ int nrhs, const mxArray *prhs[] ) /**< (name) */{ if (nrhs>0) { char name[1024]; OBJECT *obj=NULL; if (!mxIsChar(prhs[0])) output_error("entity name (arg 1) is not a string"); else if (nlhs>1) output_error("only one return value is possible"); else if (mxGetString(prhs[0],name,sizeof(name))!=0) output_error("object name too long"); else if (strcmp(name,"clock")==0) { char *fnames[] = {"timestamp","timestring","timezone"}; char buffer[256]; mxArray *pTimestamp = mxCreateDoubleMatrix(1,1,mxREAL); mxArray *pTimestring = mxCreateString(convert_from_timestamp(global_clock,buffer,sizeof(buffer))?buffer:"(error)"); mxArray *pTimezone = mxCreateString(timestamp_current_timezone()); *(double*)mxGetPr(pTimestamp) = ((double)global_clock)/TS_SECOND; plhs[0] = mxCreateStructMatrix(1,1,sizeof(fnames)/sizeof(fnames[0]),fnames); mxSetFieldByNumber(plhs[0],0,0,pTimestamp); mxSetFieldByNumber(plhs[0],0,1,pTimestring); mxSetFieldByNumber(plhs[0],0,2,pTimezone); } else if (strcmp(name,"property")==0 && nrhs>1) { if (mxGetString(prhs[1],name,sizeof(name))!=0) output_error("missing property name"); else { char classname[256]; char propname[256]; if (sscanf(name,"%[^.].%s",classname,propname)==2) { CLASS *pClass = class_get_class_from_classname(classname); if (pClass) { PROPERTY *pProp = class_find_property(pClass,propname); if (pProp) { char *fields[] = {"class","name","type","size","access","unit","delegation","keywords"}; int fn = 0; mxArray *oclass = mxCreateString(classname); mxArray *prop = mxCreateString(pProp->name); mxArray *type = mxCreateString(class_get_property_typename(pProp->ptype)); mxArray *size = mxCreateDoubleMatrix(1,1,mxREAL); mxArray *access = mxCreateString("(na)"); /** @todo implement get_property access info (ticket #187) */ mxArray *unit = mxCreateString(pProp->unit->name); mxArray *delegation = mxCreateString(pProp->delegation?pProp->delegation->oclass->name:"(none)"); mxArray *keywords = mxCreateString("(na)"); /** @todo implement get_property keywords (ticket #188) */ *(mxGetPr(size)) = pProp->size==0?1:pProp->size; plhs[0] = mxCreateStructMatrix(1,1,sizeof(fields)/sizeof(fields[0]),fields); mxSetFieldByNumber(plhs[0],0,fn++,oclass); mxSetFieldByNumber(plhs[0],0,fn++,prop); mxSetFieldByNumber(plhs[0],0,fn++,type); mxSetFieldByNumber(plhs[0],0,fn++,size); mxSetFieldByNumber(plhs[0],0,fn++,access); mxSetFieldByNumber(plhs[0],0,fn++,unit); mxSetFieldByNumber(plhs[0],0,fn++,delegation); mxSetFieldByNumber(plhs[0],0,fn++,keywords); } else output_error("property %s is not found in class %s", propname,classname); } else output_error("class %s is not found"); } else output_error("property name not in class.name format"); } } else if ((convert_to_object(name,&obj,NULL))==0) { GLOBALVAR *var = global_find(name); if (var==NULL) output_error("entity '%s' not found", name); else if (var->prop->ptype==PT_double) { size_t size = var->prop->size?var->prop->size:1; plhs[0] = mxCreateDoubleMatrix(size,1,mxREAL); memcpy(mxGetPr(plhs[0]),(void*)var->prop->addr,sizeof(double)*size); } else if (var->prop->ptype==PT_int32) { size_t size = var->prop->size?var->prop->size:1; plhs[0] = mxCreateDoubleMatrix(size,1,mxREAL); memcpy(mxGetPr(plhs[0]),(void*)var->prop->addr,sizeof(double)*size); } else if (var->prop->ptype!=PT_double) output_error("cannot retrieve globals that are of type %s",class_get_property_typename(var->prop->ptype)); } else if ((plhs[0]=get_object_data(obj))==NULL) output_error("unable to extract %s data", name);//.........这里部分代码省略.........
开发者ID:AMFIRNAS,项目名称:wso2-gridlabd,代码行数:101,
示例9: adb_main//.........这里部分代码省略......... if (auth_enabled) adb_auth_init(); // Our external storage path may be different than apps, since // we aren't able to bind mount after dropping root. const char* adb_external_storage = getenv("ADB_EXTERNAL_STORAGE"); if (NULL != adb_external_storage) { setenv("EXTERNAL_STORAGE", adb_external_storage, 1); } else { D("Warning: ADB_EXTERNAL_STORAGE is not set. Leaving EXTERNAL_STORAGE" " unchanged./n"); } /* don't listen on a port (default 5037) if running in secure mode */ /* don't run as root if we are running in secure mode */ if (should_drop_privileges()) { drop_capabilities_bounding_set_if_needed(); /* add extra groups: ** AID_ADB to access the USB driver ** AID_LOG to read system logs (adb logcat) ** AID_INPUT to diagnose input issues (getevent) ** AID_INET to diagnose network issues (netcfg, ping) ** AID_GRAPHICS to access the frame buffer ** AID_NET_BT and AID_NET_BT_ADMIN to diagnose bluetooth (hcidump) ** AID_SDCARD_R to allow reading from the SD card ** AID_SDCARD_RW to allow writing to the SD card ** AID_NET_BW_STATS to read out qtaguid statistics */ gid_t groups[] = { AID_ADB, AID_LOG, AID_INPUT, AID_INET, AID_GRAPHICS, AID_NET_BT, AID_NET_BT_ADMIN, AID_SDCARD_R, AID_SDCARD_RW, AID_NET_BW_STATS }; if (setgroups(sizeof(groups)/sizeof(groups[0]), groups) != 0) { exit(1); } /* then switch user and group to "shell" */ if (setgid(AID_SHELL) != 0) { exit(1); } if (setuid(AID_SHELL) != 0) { exit(1); } D("Local port disabled/n"); } else { char local_name[30]; build_local_name(local_name, sizeof(local_name), server_port); if(install_listener(local_name, "*smartsocket*", NULL, 0)) { exit(1); } } int usb = 0; if (access(USB_ADB_PATH, F_OK) == 0 || access(USB_FFS_ADB_EP0, F_OK) == 0) { // listen on USB usb_init(); usb = 1; } // If one of these properties is set, also listen on that port // If one of the properties isn't set and we couldn't listen on usb, // listen on the default port. property_get("service.adb.tcp.port", value, ""); if (!value[0]) { property_get("persist.adb.tcp.port", value, ""); } if (sscanf(value, "%d", &port) == 1 && port > 0) { printf("using port=%d/n", port); // listen on TCP port specified by service.adb.tcp.port property local_init(port); } else if (!usb) { // listen on default port local_init(DEFAULT_ADB_LOCAL_TRANSPORT_PORT); } D("adb_main(): pre init_jdwp()/n"); init_jdwp(); D("adb_main(): post init_jdwp()/n");#endif if (is_daemon) { // inform our parent that we are up and running.#ifdef HAVE_WIN32_PROC DWORD count; WriteFile( GetStdHandle( STD_OUTPUT_HANDLE ), "OK/n", 3, &count, NULL );#elif defined(HAVE_FORKEXEC) fprintf(stderr, "OK/n");#endif start_logging(); } D("Event loop starting/n"); fdevent_loop(); usb_cleanup(); return 0;}
开发者ID:dagix5,项目名称:android_system_core,代码行数:101,
示例10: SetBoolArg// FOR SYNCED MESSAGESvoid CGame::ActionReceived(const Action& action, int playernum){ if (action.command == "cheat") { SetBoolArg(gs->cheatEnabled, action.extra); if (gs->cheatEnabled) logOutput.Print("Cheating!"); else logOutput.Print("No more cheating"); } else if (action.command == "nohelp") { SetBoolArg(gs->noHelperAIs, action.extra); selectedUnits.PossibleCommandChange(NULL); logOutput.Print("LuaUI control is %s", gs->noHelperAIs ? "disabled" : "enabled"); } else if (action.command == "nospecdraw") { bool buf; SetBoolArg(buf, action.extra); inMapDrawer->SetSpecMapDrawingAllowed(buf); } else if (action.command == "godmode") { if (!gs->cheatEnabled) logOutput.Print("godmode requires /cheat"); else { SetBoolArg(gs->godMode, action.extra); CLuaUI::UpdateTeams(); if (gs->godMode) { logOutput.Print("God Mode Enabled"); } else { logOutput.Print("God Mode Disabled"); } CPlayer::UpdateControlledTeams(); } } else if (action.command == "globallos") { if (!gs->cheatEnabled) { logOutput.Print("globallos requires /cheat"); } else { SetBoolArg(gs->globalLOS, action.extra); if (gs->globalLOS) { logOutput.Print("Global LOS Enabled"); } else { logOutput.Print("Global LOS Disabled"); } } } else if (action.command == "nocost" && gs->cheatEnabled) { if (unitDefHandler->ToggleNoCost()) { logOutput.Print("Everything is for free!"); } else { logOutput.Print("Everything costs resources again!"); } } else if (action.command == "give" && gs->cheatEnabled) { std::string s = "give "; //FIXME lazyness s += action.extra; // .give [amount] <unitName> [team] <@x,y,z> const vector<string> &args = CSimpleParser::Tokenize(s, 0); if (args.size() < 3) { logOutput.Print("Someone is spoofing invalid .give messages!"); return; } float3 pos; if (sscanf(args[args.size() - 1].c_str(), "@%f,%f,%f", &pos.x, &pos.y, &pos.z) != 3) { logOutput.Print("Someone is spoofing invalid .give messages!"); return; } int amount = 1; int team = playerHandler->Player(playernum)->team; int allyteam = -1; int amountArgIdx = -1; int teamArgIdx = -1; if (args.size() == 5) { amountArgIdx = 1; teamArgIdx = 3; } else if (args.size() == 4) { if (args[1].find_first_not_of("0123456789") == string::npos) { amountArgIdx = 1; } else { teamArgIdx = 2; } } if (amountArgIdx >= 0) { const string& amountStr = args[amountArgIdx]; amount = atoi(amountStr.c_str()); if ((amount < 0) || (amountStr.find_first_not_of("0123456789") != string::npos)) { logOutput.Print("Bad give amount: %s", amountStr.c_str()); return; } } if (teamArgIdx >= 0) {//.........这里部分代码省略.........
开发者ID:eXLabT,项目名称:spring,代码行数:101,
示例11: mainint main(int argc, char **argv){ /* The following things are used for getopt: */ extern char *optarg; extern int optind; extern int opterr; int ch; in_addr_t dest; struct sockaddr_in destaddr,fromaddr,servaddr; socklen_t fromlen; int sockfd_r; struct hostent *hp; char *buf; char dest_str[16];#define RBLEN 500 char recbuf[RBLEN+1]; ssize_t recmegslen; fromlen = sizeof(fromaddr); // this is important otherwise recvfrom will return "Invalid argument" opterr = 0; while ((ch = getopt(argc, argv, "hp:")) != -1) { switch (ch) { case 'p': sscanf(optarg,"%d",&portnum); break; case 'h': help(); case '?': fprintf(stderr, "ERROR: No such option. -h for help./n"); exit(1); /*no default action for case */ } } if (optind != argc -2){ /* exactly two arguments must be given */ help(); } if (strlen(argv[optind])>45){ fprintf(stderr,"Error: command too long. Max is 45/n"); exit(1); } buf=argv[optind]; // hp=gethostbyname(argv[optind+1]); if (hp==NULL){ fprintf(stderr,"Error: %s is not a IP address and not a resolvable hostname/n",argv[optind+1]); exit(1); } // take the first address: strncpy(dest_str,inet_ntoa(*(struct in_addr*)hp->h_addr_list[0]),sizeof(dest_str)); dest_str[sizeof(dest_str)-1]='/0'; dest=inet_addr(dest_str); if (dest==INADDR_NONE){ fprintf(stderr,"Error: IP addr. not valid/n"); exit(1); } // printf("II: data: %s, ip: %s port: %d/n",argv[optind],dest_str,portnum); /* initialize the socket address for the destination: */ destaddr.sin_family = AF_INET; destaddr.sin_addr.s_addr = dest; destaddr.sin_port = htons(portnum); // dest port /* initialize the socket address for this server: */ servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(portnum); // source port memset(&servaddr.sin_zero, 0, sizeof(servaddr.sin_zero)); // zero fill if ((sockfd_r = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) { perror("open socket failed"); exit(1); } if (bind(sockfd_r, (struct sockaddr *)&servaddr, sizeof(servaddr))){ perror("bind socket failed"); exit(1); } // we are bound. The parent will get the message even if the sender // sends it before we call recvfrom /* the closing /0 will be sent as well: */ if(sendto(sockfd_r,buf,strlen(buf)+1,0,(struct sockaddr *)&destaddr,sizeof(destaddr)) == -1){ perror("sendto failed"); exit(1); } // we will timeout if there is no answer after a few sec signal(SIGALRM, &timeout_handler); alarm(3); recmegslen=recvfrom(sockfd_r,recbuf,RBLEN-1,0,(struct sockaddr *)&fromaddr,&fromlen); if(recmegslen == -1){ perror("recvfrom failed"); exit(1); } close(sockfd_r); recbuf[recmegslen]='/0'; printf("OK: %s: %s/n",inet_ntoa(fromaddr.sin_addr),recbuf); // return(0);}
开发者ID:ruediheimlicher,项目名称:eth_rem_dhcp,代码行数:100,
示例12: RGBE_ReadHeader/* minimal header reading. modify if you want to parse more information */int RGBE_ReadHeader(FILE *fp, int *width, int *height, rgbe_header_info *info){ char buf[128]; int found_format; float tempf; int i; found_format = 0; if (info) { info->valid = 0; info->programtype[0] = 0; info->gamma = info->exposure = 1.0; } if (fgets(buf,sizeof(buf)/sizeof(buf[0]),fp) == NULL) return rgbe_error(rgbe_read_error,NULL); if ((buf[0] != '#')||(buf[1] != '?')) { /* if you want to require the magic token then uncomment the next line */ /*return rgbe_error(rgbe_format_error,"bad initial token"); */ } else if (info) { info->valid |= RGBE_VALID_PROGRAMTYPE; for(i=0;i<sizeof(info->programtype)-1;i++) { if ((buf[i+2] == 0) || isspace(buf[i+2])) break; info->programtype[i] = buf[i+2]; } info->programtype[i] = 0; if (fgets(buf,sizeof(buf)/sizeof(buf[0]),fp) == 0) return rgbe_error(rgbe_read_error,NULL); } for(;;) {#if 0 if ((buf[0] == 0)||(buf[0] == '/n')) return rgbe_error(rgbe_format_error,"no FORMAT specifier found");#endif if (((buf[0] == 0)||(buf[0] == '/n'))&&(found_format == 0)) return rgbe_error(rgbe_format_error,"no FORMAT specifier found"); else if (strcmp(buf,"FORMAT=32-bit_rle_rgbe/n") == 0) { found_format = 1;#if 0 break; /* format found so break out of loop */#endif } else if (info && (sscanf(buf,"GAMMA=%g",&tempf) == 1)) { info->gamma = tempf; info->valid |= RGBE_VALID_GAMMA; } else if (info && (sscanf(buf,"EXPOSURE=%g",&tempf) == 1)) { info->exposure = tempf; info->valid |= RGBE_VALID_EXPOSURE; } else if (strcmp(buf,"/n") == 0) { /* blank line found so break out of loop */ break; } if (fgets(buf,sizeof(buf)/sizeof(buf[0]),fp) == 0) return rgbe_error(rgbe_read_error,NULL); } if (fgets(buf,sizeof(buf)/sizeof(buf[0]),fp) == 0) return rgbe_error(rgbe_read_error,NULL);#if 0 if (strcmp(buf,"/n") != 0) return rgbe_error(rgbe_format_error, "missing blank line after FORMAT specifier"); if (fgets(buf,sizeof(buf)/sizeof(buf[0]),fp) == 0) return rgbe_error(rgbe_read_error,NULL);#endif if (sscanf(buf,"-Y %d +X %d",height,width) < 2) return rgbe_error(rgbe_format_error,"missing image size specifier"); return RGBE_RETURN_SUCCESS;}
开发者ID:XNerv,项目名称:Fujiyama-Renderer,代码行数:72,
示例13: DBClientDataCallbackstatic pascal OSStatus DBClientDataCallback (HIViewRef browser, DataBrowserItemID itemID, DataBrowserPropertyID property, DataBrowserItemDataRef itemData, Boolean changeValue){ OSStatus err, result; CFStringRef str; Boolean r; uint32 address; uint8 value; char code[256]; result = noErr; switch (property) { case kCmCheckBox: ThemeButtonValue buttonValue; if (changeValue) { err = GetDataBrowserItemDataButtonValue(itemData, &buttonValue); citem[itemID - 1].enabled = (buttonValue == kThemeButtonOn) ? true : false; } else err = SetDataBrowserItemDataButtonValue(itemData, citem[itemID - 1].enabled ? kThemeButtonOn : kThemeButtonOff); break; case kCmAddress: if (changeValue) { err = GetDataBrowserItemDataText(itemData, &str); r = CFStringGetCString(str, code, 256, CFStringGetSystemEncoding()); CFRelease(str); if (r) { Boolean translated; if (S9xProActionReplayToRaw(code, address, value) == NULL) translated = true; else if (S9xGameGenieToRaw(code, address, value) == NULL) translated = true; else { translated = false; if (sscanf(code, "%" SCNx32, &address) != 1) address = 0; else address &= 0xFFFFFF; } citem[itemID - 1].address = address; sprintf(code, "%06" PRIX32, address); str = CFStringCreateWithCString(kCFAllocatorDefault, code, CFStringGetSystemEncoding()); err = SetDataBrowserItemDataText(itemData, str); CFRelease(str); if (translated) { DataBrowserItemID id[1]; citem[itemID - 1].value = value; id[0] = itemID; err = UpdateDataBrowserItems(browser, kDataBrowserNoItem, 1, id, kDataBrowserItemNoProperty, kCmValue); } } } else { sprintf(code, "%06" PRIX32, citem[itemID - 1].address); str = CFStringCreateWithCString(kCFAllocatorDefault, code, CFStringGetSystemEncoding()); err = SetDataBrowserItemDataText(itemData, str); CFRelease(str); } break; case kCmValue: if (changeValue) { err = GetDataBrowserItemDataText(itemData, &str); r = CFStringGetCString(str, code, 256, CFStringGetSystemEncoding()); CFRelease(str); if (r) { uint32 byte; if (sscanf(code, "%" SCNx32, &byte) == 1) citem[itemID - 1].value = (uint8) byte; else { citem[itemID - 1].value = 0; err = SetDataBrowserItemDataText(itemData, CFSTR("00")); } } } else { sprintf(code, "%02" PRIX8, citem[itemID - 1].value); str = CFStringCreateWithCString(kCFAllocatorDefault, code, CFStringGetSystemEncoding()); err = SetDataBrowserItemDataText(itemData, str);//.........这里部分代码省略.........
开发者ID:RedGuyyyy,项目名称:snes9x,代码行数:101,
示例14: WriteXTRNImagestatic MagickBooleanType WriteXTRNImage(const ImageInfo *image_info, Image *image,ExceptionInfo *exception){ Image * p; ImageInfo *clone_info; int scene; MagickBooleanType status; void *param1, *param2, *param3; param1 = param2 = param3 = (void *) NULL; status=MagickTrue; if (LocaleCompare(image_info->magick,"XTRNFILE") == 0) { clone_info=CloneImageInfo(image_info); *clone_info->magick='/0'; status=WriteImage(clone_info,image,exception); if (status == MagickFalse) CatchImageException(image); clone_info=DestroyImageInfo(clone_info); } else if (LocaleCompare(image_info->magick,"XTRNIMAGE") == 0) { Image **image_ptr; ImageInfo **image_info_ptr; clone_info=CloneImageInfo(image_info); if (clone_info->filename[0]) { (void) sscanf(clone_info->filename,"%lx,%lx",¶m1,¶m2); image_info_ptr=(ImageInfo **) param1; image_ptr=(Image **) param2; if ((image_info_ptr != (ImageInfo **) NULL) && (image_ptr != (Image **) NULL)) { *image_ptr=CloneImage(image,0,0,MagickFalse,exception); *image_info_ptr=clone_info; } } } else if (LocaleCompare(image_info->magick,"XTRNBLOB") == 0) { char **blob_data; size_t *blob_length; char filename[MagickPathExtent]; clone_info=CloneImageInfo(image_info); if (clone_info->filename[0]) { (void) sscanf(clone_info->filename,"%lx,%lx,%2048s", ¶m1,¶m2,filename); blob_data=(char **) param1; blob_length=(size_t *) param2; scene = 0; (void) CopyMagickString(clone_info->filename,filename, MagickPathExtent); for (p=image; p != (Image *) NULL; p=GetNextImageInList(p)) { (void) CopyMagickString(p->filename,filename,MagickPathExtent); p->scene=scene++; } SetImageInfo(clone_info,1,exception); (void) CopyMagickString(image->magick,clone_info->magick, MagickPathExtent); if (*blob_length == 0) *blob_length=8192; *blob_data=(char *) ImageToBlob(clone_info,image,blob_length, exception); if (*blob_data == NULL) status=MagickFalse; if (status == MagickFalse) CatchImageException(image); } clone_info=DestroyImageInfo(clone_info); } else if (LocaleCompare(image_info->magick,"XTRNARRAY") == 0) { char filename[MagickPathExtent]; size_t//.........这里部分代码省略.........
开发者ID:anorland,项目名称:ImageMagick,代码行数:101,
示例15: clearbool Image::loadPPM(const std::string &fname){ clear();/* BaseTextFile file; file.addLineCommentDef("#"); file.loadFile(fname, false); std::string type; file >> type; int nChannels; if (type == "P5") nChannels = 1; else if (type == "P6") nChannels = 3; else return false; int w, h; file >> w; file >> h; int dummy; file >> dummy; Console::print("%d %d %d/n", w, h, dummy); // Create the image create(w, h, nChannels, Image::I8BITS); // read the image data fread(&m_data[0], sizeof(unsigned char), m_data.size(), file.getFP()); return true;*/ FILE *fp; char imageType[3],str[1024]; // Read PGM image file with filename "file" // The PGM file format for a GREYLEVEL image is: // P5 (2 ASCII characters) <CR> // two ASCII numbers for nx ny (number of rows and columns <CR> // 255 (ASCII number) <CR> // binary pixel data with one byte per pixel // The PGM file format for a COLOR image is: // P6 (2 ASCII characters) <CR> // two ASCII numbers for nx ny (number of rows and columns <CR> // 255 (ASCII number) <CR> // binary pixel data with three bytes per pixel (one byte for eacg RGB) fp=fopen(fname.c_str(),"rb"); if (!fp) return false; // read the first ASCII line to find out if we read a color image or // a greylevel image fgets(str,100,fp); sscanf(str,"%s",imageType); Format format = Image::I8BITS; int nChannels = 0; if(!strncmp(imageType,"P5",2)) // greylevel image nChannels = 1; else if(!strncmp(imageType,"P6",2)) // color image nChannels = 3; else return false; // skip comments embedded in header fgets(str,1024,fp); while(str[0]=='#') fgets(str,1024,fp); // read image dimensions int w, h; sscanf(str,"%d %d", &w, &h); // read the next line into dummy variable fgets(str,1024,fp); // Create the image create(w, h, nChannels, format); // read the image data fread(&m_data[0], sizeof(unsigned char), w*h*m_bytesPerPixel, fp); fclose(fp); if (m_width==0 || m_height==0) return false; return true;}
开发者ID:ennioquaglia,项目名称:GameEngine,代码行数:93,
示例16: WaitressFetchCall//.........这里部分代码省略......... WRITE_RET ("/r/n", 2); if (waith->method == WAITRESS_METHOD_POST && waith->postData != NULL) { WRITE_RET (waith->postData, strlen (waith->postData)); } /* receive answer */ nextLine = recvBuf; while (hdrParseMode != HDRM_FINISHED) { READ_RET (recvBuf+bufFilled, sizeof (recvBuf)-1 - bufFilled, &recvSize); if (recvSize == 0) { /* connection closed too early */ CLOSE_RET (WAITRESS_RET_CONNECTION_CLOSED); } bufFilled += recvSize; memset (recvBuf+bufFilled, 0, sizeof (recvBuf) - bufFilled); thisLine = recvBuf; /* split */ while ((nextLine = strchr (thisLine, '/n')) != NULL && hdrParseMode != HDRM_FINISHED) { /* make lines parseable by string routines */ *nextLine = '/0'; if (*(nextLine-1) == '/r') { *(nextLine-1) = '/0'; } /* skip /0 */ ++nextLine; switch (hdrParseMode) { /* Status code */ case HDRM_HEAD: if (sscanf (thisLine, "HTTP/1.%*1[0-9] %3[0-9] ", statusCode) == 1) { if (memcmp (statusCode, "200", 3) == 0 || memcmp (statusCode, "206", 3) == 0) { /* everything's fine... */ } else if (memcmp (statusCode, "403", 3) == 0) { CLOSE_RET (WAITRESS_RET_FORBIDDEN); } else if (memcmp (statusCode, "404", 3) == 0) { CLOSE_RET (WAITRESS_RET_NOTFOUND); } else { CLOSE_RET (WAITRESS_RET_STATUS_UNKNOWN); } hdrParseMode = HDRM_LINES; } /* endif */ break; /* Everything else, except status code */ case HDRM_LINES: /* empty line => content starts here */ if (*thisLine == '/0') { hdrParseMode = HDRM_FINISHED; } else { memset (val, 0, sizeof (val)); if (sscanf (thisLine, "Content-Length: %255c", val) == 1) { waith->contentLength = atol (val); } } break; default: break; } /* end switch */ thisLine = nextLine;
开发者ID:landonf,项目名称:pianobar,代码行数:67,
示例17: dsetInit_devAiAsyncSerial/* initialize the epics record and the hardware */static long dsetInit_devAiAsyncSerial(aiRecord *pai){ CONTEXT *p_myContext; CALLBACK *p_myCallback; char p_writeBuffer[BUFLEN]; char p_readBuffer[BUFLEN]; int myPrimaryAddress; int myPortNumber; int myParity; int myNumberOfDataBits; int myNumberOfStopBits; int myBaudRate; char p_myCommand[BUFLEN]; #ifdef DEBUG1 packageInfo(); printf(__FILE__ "[%d] -> %s (%s)/n", __LINE__, __func__, pai->name); #endif /* Parse the db file paramters */ /* and set the value of key variables */ if(sscanf(pai->inp.value.instio.string, "spn=%d pad=%d br=%d nodb=%d p=%d nosb=%d c=%[^/n]", &myPortNumber, &myPrimaryAddress, &myBaudRate, &myNumberOfDataBits, &myParity, &myNumberOfStopBits, p_myCommand)!=7) { printf( __FILE__ "[%d] Error: Couldn't parse the parameters correctly!", __LINE__ ); printf( __FILE__ "[%d] >%s<!", __LINE__, pai->inp.value.instio.string ); sleep(SLEEPTIME_ERROR); return(ERROR); } /* end_of_if */ initSerialPort2(myPortNumber); setBaudRate2(myPortNumber,myBaudRate); setNumberOfDataBits2(myPortNumber,myNumberOfDataBits); setParity2(myPortNumber,myParity); setFlowControl2(myPortNumber,NO_FLOW_CONTROL); /* Required for this dev */ setNumberOfStopBits2(myPortNumber,myNumberOfStopBits); #ifdef DEBUG2 printf(__FILE__ "[%d] portNumber = %d/n", __LINE__, myPortNumber); printf(__FILE__ "[%d] primaryAddress = %d/n", __LINE__, myPrimaryAddress); printf(__FILE__ "[%d] baudRate = %d/n", __LINE__, getBaudRate2(myPortNumber)); printf(__FILE__ "[%d] numberOfDataBits = %d/n", __LINE__, getNumberOfDataBits2(myPortNumber)); printf(__FILE__ "[%d] parity = %d/n", __LINE__, getParity2(myPortNumber)); printf(__FILE__ "[%d] numberOfStopBits = %d/n", __LINE__, getNumberOfStopBits2(myPortNumber)); printf(__FILE__ "[%d] p_myCommand = >%s</n", __LINE__, p_myCommand); #endif if (lockSerialPort2(myPortNumber,LOCK, pai->name)<=ERROR) { printf( __FILE__ "[%d] Error: Couldn't lock serial port (%s)/n", __LINE__, getSerialPortName2(myPortNumber)); sleep(SLEEPTIME_ERROR); return(ERROR); } /* Disable front panel */ /* This operation should work if */ /* communication parameters are ok */ strcpy(p_writeBuffer,"XFRONT"); strcat(p_writeBuffer,TERMINATOR); openSerialPort2(myPortNumber); if (writeSerialPort2(myPortNumber, p_writeBuffer ) <= ERROR) { printf( __FILE__ "[%d] Error: Couldn't write on %s/n", __LINE__, getSerialPortName2(myPortNumber)); sleep(SLEEPTIME_ERROR); return(ERROR); } usleep(USLEEPTIME_WRITE); memset(p_readBuffer,0,BUFLEN); if (readSerialPort2(myPortNumber, p_readBuffer, BUFLEN) <= ERROR) { printf( __FILE__ "[%d] Error: Couldn't read on %s/n", __LINE__, getSerialPortName2(myPortNumber)); sleep(SLEEPTIME_ERROR); return(ERROR); } usleep(USLEEPTIME_READ); if (lockSerialPort2(myPortNumber,UNLOCK, pai->name)<=ERROR) { printf ( __FILE__ "Error"); sleep(SLEEPTIME_ERROR); return(ERROR); } p_myCallback=(CALLBACK *)calloc(1,sizeof(CALLBACK)); callbackSetCallback(myCallback_devAiAsyncSerial,p_myCallback); callbackSetUser(pai,p_myCallback); p_myContext=(CONTEXT *)calloc(1,sizeof(CONTEXT)); p_myContext->portNumber=myPortNumber;//.........这里部分代码省略.........
开发者ID:emayssat,项目名称:epics-iocs,代码行数:101,
示例18: port_io/* * Read and write all the ports specified in hex on the command line. * The program uses the faster ioperm[set port IO permissions]/iopl[change IO privilege level] calls on x86. * The program acts as inb/inw/inl according to its own name. */int port_io(int argc, char **argv){ unsigned int i, n, port, size, error = 0; unsigned int val, opt; prgname = argv[0]; switch (prgname[strlen(prgname)-1]) { case 'w': size = 2; break; case 'l': size = 4; break; case 'b': case 'p': default: size = 1; } setuid(0); printf("Please choose the option: 1 - read, 2 - write: "); scanf("%d",&opt); if (opt == 1) { for (i = 1; i < argc; i++) { if ( sscanf(argv[i], "%x%n", &port, &n) < 1 || n != strlen(argv[i]) ) { fprintf(stderr, "%s: argument /"%s/" is not a hex number/n", argv[0], argv[i]); error++; continue; } if (port & (size-1)) { fprintf(stderr, "%s: argument /"%s/" is not properly aligned/n", argv[0], argv[i]); error++; continue; } error += read_one(port, size); } } else if (opt == 2) { for (i = 1; i < argc-1; i++) { if ( sscanf(argv[i], "%x%n", &port, &n) < 1 || n != strlen(argv[i]) ) { fprintf(stderr, "%s: argument /"%s/" is not a hex number/n", argv[0], argv[i]); error++; continue; } if (port & (size-1)) { fprintf(stderr, "%s: argument /"%s/" is not properly aligned/n", argv[0], argv[i]); error++; continue; } if ( sscanf(argv[i+1], "%x%n", &val, &n) < 1 || n != strlen(argv[i+1]) ) { fprintf(stderr, "%s: argument /"%s/" is not a hex number/n", argv[0], argv[i+1]); error++; continue; } if (size < 4 && val > (size == 1 ? 0xff : 0xffff)) { fprintf(stderr, "%s: argument /"%s/" out of range/n", argv[0], argv[i+1]); error++; continue; } error += write_one(port, val, size); } } return (error ? 1 : 0);}
开发者ID:beike2020,项目名称:source,代码行数:81,
示例19: rgzmat/* GZMAT */int rgzmat(char *filename, int *atomnum, ATOM * atom, CONTROLINFO cinfo, MOLINFO minfo){ typedef struct { char name[MAXCHAR]; } STRNAME; FILE *fpin; int i, j, index, index0; int overflow_flag = 0; int findindex; int numatom; int coordinate_flag = 0; STRNAME *bondstr; STRNAME *anglestr; STRNAME *twiststr; char tmpchar1[MAXCHAR]; char tmpchar2[MAXCHAR]; char line[MAXCHAR]; if ((fpin = fopen(filename, "r")) == NULL) { fprintf(stdout, "Cannot open the input file %s to read in rgzmat(), exit/n", filename); exit(1); } bondstr = (STRNAME *) malloc(sizeof(STRNAME) * (cinfo.maxatom +10)); if (bondstr == NULL) { fprintf(stdout, "memory allocation error for *bondstr in rgzmat()/n"); exit(1); } anglestr = (STRNAME *) malloc(sizeof(STRNAME) * (cinfo.maxatom +10)); if (anglestr == NULL) { fprintf(stdout, "memory allocation error for *anglestr in rgzmat()/n"); exit(1); } twiststr = (STRNAME *) malloc(sizeof(STRNAME) * (cinfo.maxatom +10)); if (twiststr == NULL) { fprintf(stdout, "memory allocation error for *twiststr in rgzmat()/n"); exit(1); } initial(cinfo.maxatom, atom, minfo.resname); index = 0; index0 = 1; numatom = 0; for (;;) { if (fgets(line, MAXCHAR, fpin) == NULL) {/* printf("/nFinished reading %s file.", cinfo.ifilename); */ break; } if (spaceline(line) == 1) { if(coordinate_flag == 1) break; index++; continue; } if (index >= 2) index++; if (index <= 3) continue; if (index >= 4) { if (spaceline(line) == 1 || strncmp(line, "Vari", 4) == 0 || strncmp(line, "vari", 4) == 0) index0 = -1; if (strncmp(line, "Const", 5) == 0 || strncmp(line, "const", 5) == 0) index0 = -1; } if (index == 4) { if (overflow_flag == 0) sscanf(line, "%s", atom[numatom].name); numatom++; if (numatom >= cinfo.maxatom && overflow_flag == 0) { printf ("/nInfo: the atom number exceeds the MAXATOM, reallocate memory automatically"); overflow_flag = 1; } continue; } if (index == 5) { if (overflow_flag == 0) { sscanf(line, "%s%d%s", atom[numatom].name, &atom[numatom].bondatom, bondstr[numatom].name); if(atom[numatom].bondatom > numatom) { printf("/nError: bond atom ID is larger than ID of current atom (%d,%s), exit", numatom+1, atom[numatom].name); exit(1); } } numatom++; if (numatom >= cinfo.maxatom && overflow_flag == 0) { printf ("/nInfo: the atom number exceeds the MAXATOM, reallocate memory automatically"); overflow_flag = 1; } continue; } if (index == 6) { if (overflow_flag == 0) { sscanf(line, "%s%d%s%d%s", atom[numatom].name,//.........这里部分代码省略.........
开发者ID:tianhe2,项目名称:mAMBER,代码行数:101,
示例20: Load// Attempts to load the texture from the source.bool TextureResource::Load(RenderInterface* render_interface) const{ // Check for special loader tokens. if (!source.Empty() && source[0] == '?') { Vector2i dimensions; bool delete_data = false; const byte* data = NULL; // Find the generation protocol and generate the data accordingly. String protocol = source.Substring(1, source.Find("::") - 1); if (protocol == "font") { // The requested texture is a font layer. delete_data = true; FontFaceHandle* handle; FontEffect* layer_id; int layout_id; int texture_id; if (sscanf(source.CString(), "?font::%p/%p/%d/%d", &handle, &layer_id, &layout_id, &texture_id) == 4) { handle->GenerateLayerTexture(data, dimensions, layer_id, layout_id, texture_id); } } // If texture data was generated, great! Otherwise, fallback to the LoadTexture() code and // hope the client knows what the hell to do with the question mark in their file name. if (data != NULL) { TextureHandle handle; bool success = render_interface->GenerateTexture(handle, data, dimensions); if (delete_data) delete[] data; if (success) { texture_data[render_interface] = TextureData(handle, dimensions); return true; } else { Log::Message(Log::LT_WARNING, "Failed to generate internal texture %s.", source.CString()); texture_data[render_interface] = TextureData(0, Vector2i(0, 0)); return false; } } } TextureHandle handle; Vector2i dimensions; if (!render_interface->LoadTexture(handle, dimensions, source)) { Log::Message(Log::LT_WARNING, "Failed to load texture from %s.", source.CString()); texture_data[render_interface] = TextureData(0, Vector2i(0, 0)); return false; } texture_data[render_interface] = TextureData(handle, dimensions); return true;}
开发者ID:Foe-of-Eternity,项目名称:Unvanquished,代码行数:72,
示例21: wgzmatvoid wgzmat(char *filename, int atomnum, ATOM atom[], MOLINFO minfo){ FILE *fpin; FILE *fpout; char *amberhome; char espparm_file[MAXCHAR]; char line[MAXCHAR]; char akeyword[MAXCHAR]=""; char ckeyword[MAXCHAR]; char tmpchar0[MAXCHAR]; char tmpchar1[MAXCHAR]; char tmpchar2[MAXCHAR]; char tmpchar3[MAXCHAR]; int i,j; int iradius_flag; int ibs= 0; int esp_flag; int nespparm = 0; int nbasisset = 0; double default_radius = 1.7; ESPPARM espparm[120]; BASISSET basisset[100]; if ((fpout = fopen(filename, "w")) == NULL) { fprintf(stdout, "Cannot open a file %s to write in wgzmat(), exit/n", filename); exit(1); } intercoord(atomnum, atom); fprintf(fpout, "%s/n", "--Link1--"); if(strlen(minfo.gn) >= 5) fprintf(fpout, "%s/n", minfo.gn); fprintf(fpout, "%s%s/n", "%chk=", minfo.chkfile); if(strlen(minfo.gm) >= 4) fprintf(fpout, "%s/n", minfo.gm);// check ESP-related keyword esp_flag = 0; for(i=0;i<strlen(minfo.gkeyword);i++) ckeyword[i] = toupper(minfo.gkeyword[i]); if((strstr(ckeyword, "POP=") != 0 || strstr(ckeyword, "POP(") != 0) && (strstr(ckeyword, "MK") != 0 || strstr(ckeyword, "CHELP") != 0)) esp_flag = 1;// when the default gaussian keyword is used, or esp_flag ==1, read ESP.PARM if(minfo.igkeyword == 0 || esp_flag == 1) { amberhome = (char *) getenv("AMBERHOME"); if( amberhome == NULL ){ fprintf( stdout, "AMBERHOME is not set!/n" ); exit(1); } strcpy(espparm_file, amberhome); strcat(espparm_file, "/dat/antechamber/ESPPARM.DAT"); if ((fpin = fopen(espparm_file, "r")) == NULL) { fprintf(stdout, "Cannot open espparm_file %s in read_espparm(), exit/n", espparm_file); exit(1); } for (;;) { if (fgets(line, MAXCHAR, fpin) == NULL) break; if(strncmp(line, "DEFAULT RADIUS", 14) == 0) sscanf(&line[14], "%lf", &default_radius); if(strncmp(line, "BASIS SET", 9) == 0) { sscanf(&line[9], "%d%s", &basisset[nbasisset].id, basisset[nbasisset].bs); nbasisset++; } if(strncmp(line, "PARM", 4) == 0) { sscanf(&line[4], "%ld%s%lf%lf%d%d", &espparm[nespparm].atomicnum, espparm[nespparm].elem, &espparm[nespparm].vdw, &espparm[nespparm].mk, &espparm[nespparm].flag, &espparm[nespparm].bs); nespparm++; } } fclose(fpin); iradius_flag = 0; ibs = 0; for(i=0;i<atomnum;i++) { for(j=0;j<nespparm;j++) if(atom[i].atomicnum == espparm[j].atomicnum || strcmp(atom[i].element, espparm[j].elem) == 0) { if(ibs < espparm[j].bs) ibs=espparm[j].bs; if(espparm[j].flag != 0) { iradius_flag = 1; espparm[j].flag = 2; } break; } } if(minfo.igkeyword == 0) { strcpy(minfo.gkeyword, "#HF/"); strcat(minfo.gkeyword, basisset[ibs-1].bs); strcat(minfo.gkeyword, " SCF=tight Test Pop=MK iop(6/33=2) iop(6/42=6) opt"); } }// additional keywords if(esp_flag == 1) { if(iradius_flag == 1) { if(strstr(minfo.gkeyword, "ReadRadii") == 0 && strstr(minfo.gkeyword, "READRADII") == 0 && strstr(minfo.gkeyword, "readradii") == 0) {//.........这里部分代码省略.........
开发者ID:tianhe2,项目名称:mAMBER,代码行数:101,
示例22: namedColorFilePathvoidKPaletteTable::readNamedColor( void ){ if( mNamedColorList->count() != 0 ) { return; // Strings already present } TDEGlobal::locale()->insertCatalogue("tdelibs_colors"); // // Code somewhat inspired by KPalette. // const char * const *path = namedColorFilePath(); for( int i=0; path[i]; ++i ) { TQFile paletteFile( path[i] ); if( !paletteFile.open( IO_ReadOnly ) ) { continue; } TQString line; TQStringList list; while( paletteFile.readLine( line, 100 ) != -1 ) { int red, green, blue; int pos = 0; if( sscanf(line.ascii(), "%d %d %d%n", &red, &green, &blue, &pos ) == 3 ) { // // Remove duplicates. Every name with a space and every name // that start with "gray". // TQString name = line.mid(pos).stripWhiteSpace(); if( name.isNull() || name.find(' ') != -1 || name.find( "gray" ) != -1 || name.find( "grey" ) != -1 ) { continue; } const TQColor color ( red, green, blue ); if ( color.isValid() ) { const TQString colorName( i18n("color", name.latin1() ) ); list.append( colorName ); d->m_namedColorMap[ colorName ] = color; } } } list.sort(); mNamedColorList->insertStringList( list ); break; } if( mNamedColorList->count() == 0 ) { // // Give the error dialog box a chance to center above the // widget (or dialog). If we had displayed it now we could get a // situation where the (modal) error dialog box pops up first // preventing the real dialog to become visible until the // error dialog box is removed (== bad UI). // TQTimer::singleShot( 10, this, TQT_SLOT(slotShowNamedColorReadError()) ); }}
开发者ID:Fat-Zer,项目名称:tdelibs,代码行数:70,
示例23: main//.........这里部分代码省略......... else { data->north_bounding = xml_get_double_value(doc, "metadata.idinfo.spdom.bounding.northbc"); //printf("West bounding coordinate: %.4lf/n", data->north_bounding); } // South bounding coordinate fValue = xml_get_double_value(doc, "metadata.idinfo.spdom.bounding.southbc"); if (fValue < -90.0 || fValue > 90.0) { error = TRUE; sprintf(tmp, "South bounding coordinate - Value (%.4lf) outside the " "expected value range (-90.0 < value < 90.0)/n", fValue); strcat(errorMessage, tmp); } else { data->south_bounding = xml_get_double_value(doc, "metadata.idinfo.spdom.bounding.southbc"); //printf("South bounding coordinate: %.4lf/n", data->south_bounding); } // Open KML for reading char centerFile[512], boundaryFile[512], *baseName; char coordStr[50]; float height; baseName = get_basename(inFile); sprintf(boundaryFile, "%s_boundary.kml", baseName); sprintf(centerFile, "%s_center.kml", baseName); xmlDoc *xmlBoundary = xmlReadFile(boundaryFile, NULL, 0); if (!xmlBoundary) asfPrintError("Could not parse boundary file (%s)/n", boundaryFile); else { strcpy(coordStr, xml_get_string_value(xmlBoundary, "kml.Document.Placemark.Polygon.outerBoundaryIs.LinearRing.coordinates")); sscanf(coordStr, "%f,%f,%f/n%f,%f,%f/n%f,%f,%f/n%f,%f", &data->near_start_lat, &data->near_start_lon, &height, &data->near_end_lat, &data->near_end_lon, &height, &data->far_end_lat, &data->far_end_lon, &height, &data->far_start_lat, &data->far_start_lon); //printf("Near start latitude: %.4f/n", data->near_start_lat); //printf("Near start longitude: %.4f/n", data->near_start_lon); //printf("Near end latitude: %.4f/n", data->near_end_lat); //printf("Near end longitude: %.4f/n", data->near_end_lon); //printf("Far start latitude: %.4f/n", data->far_start_lat); //printf("Far start longitude: %.4f/n", data->far_start_lon); //printf("Far end latitude: %.4f/n", data->far_end_lat); //printf("Far end longitude: %.4f/n", data->far_end_lon); } xmlFreeDoc(xmlBoundary); xmlDoc *xmlCenter = xmlReadFile(centerFile, NULL, 0); if (!xmlCenter) asfPrintWarning("Could not parse center point file (%s)/n", centerFile); else { strcpy(coordStr, xml_get_string_value(xmlCenter, "kml.Document.Placemark.Point.coordinates")); sscanf(coordStr, "%f,%f", &data->center_lat, &data->center_lon); //printf("Center latitude: %.4f/n", data->center_lat); //printf("Center longitude: %.4f/n", data->center_lon); } xmlFreeDoc(xmlCenter); // Processing level strcpy(string, xml_get_string_value(doc, "metadata.idinfo.proclevl.prolevid")); if (strlen(string) > MAX_PROCESSING_LEVEL) { error = TRUE;
开发者ID:DavinSimmons,项目名称:ASF_MapReady,代码行数:67,
示例24: M_LoadDefaultsvoid M_LoadDefaults (void){ int i; int len; FILE* f; char def[80]; char strparm[100]; char* newstring = NULL; // killough int parm; boolean isstring; // set everything to base values numdefaults = sizeof(defaults) / sizeof(defaults[0]); for (i = 0 ; i < numdefaults ; i++) { if (defaults[i].location.ppsz) *defaults[i].location.ppsz = strdup(defaults[i].defaultvalue.psz); if (defaults[i].location.pi) *defaults[i].location.pi = defaults[i].defaultvalue.i; } // check for a custom default file#if ((defined GL_DOOM) && (defined _MSC_VER))#define BOOM_CFG "glboom.cfg"#else#define BOOM_CFG "prboom.cfg"#endif i = M_CheckParm ("-config"); if (i && i < myargc-1) defaultfile = strdup(myargv[i+1]); else { const char* exedir = I_DoomExeDir(); /* get config file from same directory as executable */#if 1 int len = doom_snprintf(NULL, 0, BOOM_CFG); defaultfile = malloc(len+1); doom_snprintf(defaultfile, len+1, BOOM_CFG);#else int len = doom_snprintf(NULL, 0, "%s/" BOOM_CFG, exedir); defaultfile = malloc(len+1); doom_snprintf(defaultfile, len+1, "%s/" BOOM_CFG, exedir);#endif } lprintf (LO_CONFIRM, " default file: %s/n",defaultfile); // read the file in, overriding any set defaults f = fopen (defaultfile, "r"); if (f) { while (!feof(f)) { isstring = false; if (fscanf (f, "%79s %[^/n]/n", def, strparm) == 2) { //jff 3/3/98 skip lines not starting with an alphanum if (!isalnum(def[0])) continue; if (strparm[0] == '"') { // get a string default isstring = true; len = strlen(strparm); newstring = (char *) malloc(len); strparm[len-1] = 0; // clears trailing double-quote mark strcpy(newstring, strparm+1); // clears leading double-quote mark } else if ((strparm[0] == '0') && (strparm[1] == 'x')) { // CPhipps - allow ints to be specified in hex sscanf(strparm+2, "%x", &parm); } else { sscanf(strparm, "%i", &parm); // Keycode hack removed } for (i = 0 ; i < numdefaults ; i++) if ((defaults[i].type != def_none) && !strcmp(def, defaults[i].name)) { // CPhipps - safety check if (isstring != IS_STRING(defaults[i])) { lprintf(LO_WARN, "M_LoadDefaults: Type mismatch reading %s/n", defaults[i].name); continue; } if (!isstring) { //jff 3/4/98 range check numeric parameters if ((defaults[i].minvalue==UL || defaults[i].minvalue<=parm) && (defaults[i].maxvalue==UL || defaults[i].maxvalue>=parm)) *(defaults[i].location.pi) = parm; } else { union { const char **c; char **s; } u; // type punning via unions//.........这里部分代码省略.........
开发者ID:Arc0re,项目名称:prboom3ds,代码行数:101,
示例25: gw_dm_listenervoid gw_dm_listener(void *arg){ fd_set in_pipes; int i, j,num_mads; int greater, rc, rcm; char c; char info[GW_DM_MAX_INFO]; char s_id[GW_DM_MAX_ID]; char result[GW_DM_MAX_RESULT]; char action[GW_DM_MAX_ACTION]; char str[GW_DM_MAX_STRING]; char *s_host_id, *queue_name, *s_rank, *lasts; int job_id, host_id, rank; gw_dm_mad_t * dm_mad; pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL); pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL); while (1) { greater = gw_dm_set_pipes (&in_pipes, &num_mads); select( greater+1, &in_pipes, NULL, NULL, NULL); for (i= 0; i<=greater; i++) { if ( FD_ISSET(i, &in_pipes) ) { dm_mad = gw_dm_get_mad_by_fd(i); if ( dm_mad == NULL ) continue; j = 0; do { rc = read(i, (void *) &c, sizeof(char)); str[j++] = c; } while ((rc > 0) && (c != '/n') && (j < (GW_DM_MAX_STRING-1))); str[j] = '/0'; if (rc <= 0) /* Error Reading message from MAD! */ { gw_log_print("DM",'W',"Error reading MAD (%s) message/n", dm_mad->name); pthread_mutex_lock(&(gw_dm.mutex)); gw_dm.scheduling = GW_TRUE; /* Prevents to call the scheduler while recovering*/ pthread_mutex_unlock(&(gw_dm.mutex)); rcm = gw_dm_mad_reload(dm_mad); if ( rcm == 0 ) { gw_log_print("DM",'I',"MAD (%s) successfully reloaded/n", dm_mad->name); gw_user_pool_dm_recover(dm_mad); gw_host_pool_dm_recover(dm_mad); gw_job_pool_dm_recover(dm_mad); } else { gw_log_print("DM",'E',"Error reloading the scheduler (%s)/n", dm_mad->name); dm_mad->mad_dm_pipe = -1; if ( num_mads == 1 ) { gw_log_print("DM",'E',"GridWay needs to be restarted! (no scheduler)/n"); return; } } pthread_mutex_lock(&(gw_dm.mutex)); gw_dm.scheduling = GW_FALSE; /* Activate the scheduler again*/ pthread_mutex_unlock(&(gw_dm.mutex)); continue; } info[0] = '/0'; sscanf(str,"%" GW2STR(GW_DM_MAX_ACTION) "s %" GW2STR(GW_DM_MAX_ID) "s %" GW2STR(GW_DM_MAX_RESULT) "s %" GW2STR(GW_DM_MAX_INFO) "[^/n]", action, s_id, //.........这里部分代码省略.........
开发者ID:GridWay,项目名称:gridway,代码行数:101,
示例26: XmuReadBitmapData/* * The data returned by the following routine is always in left-most byte * first and left-most bit first. If it doesn't return BitmapSuccess then * its arguments won't have been touched. This routine should look as much * like the Xlib routine XReadBitmapfile as possible. */int XmuReadBitmapData ( FILE *fstream, /* handle on file */ unsigned int *width, /* RETURNED */ unsigned int *height, /* RETURNED */ unsigned char **datap, /* RETURNED */ int *x_hot, int *y_hot) /* RETURNED */{ unsigned char *data = NULL; /* working variable */ char line[MAX_SIZE]; /* input line from file */ int size; /* number of bytes of data */ char name_and_type[MAX_SIZE]; /* an input line */ char *type; /* for parsing */ int value; /* from an input line */ int version10p; /* boolean, old format */ int padding; /* to handle alignment */ int bytes_per_line; /* per scanline of data */ unsigned int ww = 0; /* width */ unsigned int hh = 0; /* height */ int hx = -1; /* x hotspot */ int hy = -1; /* y hotspot */#ifndef Xmalloc#define Xmalloc(size) malloc(size)#endif /* first time initialization */ if (!hex_initialized) initHexTable(); /* error cleanup and return macro */#define RETURN(code) { if (data) free (data); return code; } while (fgets(line, MAX_SIZE, fstream)) { if (strlen(line) == MAX_SIZE-1) { RETURN (BitmapFileInvalid); } if (sscanf(line,"#define %s %d",name_and_type,&value) == 2) { if (!(type = strrchr(name_and_type, '_'))) type = name_and_type; else type++; if (!strcmp("width", type)) ww = (unsigned int) value; if (!strcmp("height", type)) hh = (unsigned int) value; if (!strcmp("hot", type)) { if (type-- == name_and_type || type-- == name_and_type) continue; if (!strcmp("x_hot", type)) hx = value; if (!strcmp("y_hot", type)) hy = value; } continue; } if (sscanf(line, "static short %s = {", name_and_type) == 1) version10p = 1; else if (sscanf(line,"static unsigned char %s = {",name_and_type) == 1) version10p = 0; else if (sscanf(line, "static char %s = {", name_and_type) == 1) version10p = 0; else continue; if (!(type = strrchr(name_and_type, '_'))) type = name_and_type; else type++; if (strcmp("bits[]", type)) continue; if (!ww || !hh) RETURN (BitmapFileInvalid); if ((ww % 16) && ((ww % 16) < 9) && version10p) padding = 1; else padding = 0; bytes_per_line = (ww+7)/8 + padding; size = bytes_per_line * hh; data = (unsigned char *) Xmalloc ((unsigned int) size); if (!data) RETURN (BitmapNoMemory); if (version10p) { unsigned char *ptr; int bytes; for (bytes=0, ptr=data; bytes<size; (bytes += 2)) { if ((value = NextInt(fstream)) < 0)//.........这里部分代码省略.........
开发者ID:boukeversteegh,项目名称:chise,代码行数:101,
示例27: ThrowReaderExceptionstatic Image *ReadXTRNImage(const ImageInfo *image_info, ExceptionInfo *exception){ Image *image; ImageInfo *clone_info; void *param1, *param2, *param3; param1 = param2 = param3 = (void *) NULL; image = (Image *) NULL; clone_info=CloneImageInfo(image_info); if (clone_info->filename == NULL) { clone_info=DestroyImageInfo(clone_info); ThrowReaderException(FileOpenWarning,"No filename specified"); } if (LocaleCompare(image_info->magick,"XTRNFILE") == 0) { image=ReadImage(clone_info,exception); CatchException(exception); } else if (LocaleCompare(image_info->magick,"XTRNIMAGE") == 0) { Image **image_ptr;#ifdef ALL_IMAGEINFO ImageInfo **image_info_ptr;#endif (void) sscanf(clone_info->filename,"%lx,%lx",¶m1,¶m2); image_ptr=(Image **) param2; if (*image_ptr != (Image *) NULL) image=CloneImage(*image_ptr,0,0,MagickFalse,exception);#ifdef ALL_IMAGEINFO image_info_ptr=(ImageInfo **) param1; if (*image_info_ptr != (ImageInfo *) NULL) image_info=*image_info_ptr;#endif } else if (LocaleCompare(image_info->magick,"XTRNBLOB") == 0) { char **blob_data; size_t *blob_length; char filename[MagickPathExtent]; (void) sscanf(clone_info->filename,"%lx,%lx,%2048s",¶m1,¶m2, filename); blob_data=(char **) param1; blob_length=(size_t *) param2; image=BlobToImage(clone_info,*blob_data,*blob_length,exception); CatchException(exception); } else if (LocaleCompare(image_info->magick,"XTRNARRAY") == 0) { char *blob_data, filename[MagickPathExtent]; HRESULT hr; long lBoundl, lBoundu; SAFEARRAY *pSafeArray; size_t blob_length; *filename='/0'; (void) sscanf(clone_info->filename,"%lx,%2048s",¶m1,filename); hr=S_OK; pSafeArray=(SAFEARRAY *) param1; if (pSafeArray) { hr = SafeArrayGetLBound(pSafeArray, 1, &lBoundl); if (SUCCEEDED(hr)) { hr = SafeArrayGetUBound(pSafeArray, 1, &lBoundu); if (SUCCEEDED(hr)) { blob_length = lBoundu - lBoundl + 1; hr = SafeArrayAccessData(pSafeArray,(void**) &blob_data); if(SUCCEEDED(hr)) {//.........这里部分代码省略.........
开发者ID:anorland,项目名称:ImageMagick,代码行数:101,
示例28: get_pid_by_nameunsigned int get_pid_by_name(const char *pro_name){ /* * search /proc/pid/status to find program's name * and then we can find the pid */ unsigned int pid = 1; // search start FILE *filp = NULL; char proc_status[20] = {0}; char status_info[100] = {0}; //file status information store in this char cur_name[100] = {0}; //program's name's max lenght unsigned int pid_max = get_sys_max_pid(); //max pid while (1) { /* * open 1 program's status file, then read data */ sprintf(proc_status, "/proc/%u/status", pid);#ifdef DEBUG printf("proc_status: %s, led: %d/n", proc_status, strlen(proc_status));#endif filp = fopen(proc_status, "r"); if (!filp) {#ifdef DEBUG perror("fopen");#endif if (pid >= pid_max) { fprintf(stderr, "Can not find pid of program %s/n", pro_name); break; } /* * current pid is no exist, go to search next */ pid++; continue; } /* * get one line to sparse by loop */ while ((!feof(filp)) && (fgets(status_info, 99, filp))) { if (sscanf(status_info, "Name: %s", cur_name) == 1) { /* * Run here means that we got current program's name, * next what we should do is to compare. */ if (!strcmp(cur_name, pro_name)) { fclose(filp); return pid; } /* * Not match, search next pid. */ bzero(cur_name, sizeof(cur_name)); break; } /* * Didn't scan target, scan next line. */ bzero(status_info, sizeof(status_info)); } /* end of one pid */ pid++; fclose(filp); bzero(status_info, sizeof(status_info)); } return 0; /* Haven't find the pid, return 0 */}
开发者ID:cyhhong,项目名称:exercise_programs,代码行数:70,
示例29: cmd_bp/* Breakpoint command */int cmd_bp(){ char *str; int ret; eresi_Addr addr; char logbuf[BUFSIZ]; int idx; int index; elfsh_SAddr off = 0; char *name; elfshbp_t *cur; char **keys; int keynbr; PROFILER_IN(__FILE__, __FUNCTION__, __LINE__); /* build argc */ for (idx = 0; world.curjob->curcmd->param[idx] != NULL; idx++); str = revm_lookup_string(world.curjob->curcmd->param[0]); /* Select subcommand */ switch (idx) { /* List breakpoints */ case 0: e2dbg_output(" .:: Breakpoints ::./n/n"); keys = hash_get_keys(&e2dbgworld.bp, &keynbr); for (index = 0; index < keynbr; index++) { cur = hash_get(&e2dbgworld.bp, keys[index]); name = revm_resolve(world.curjob->curfile, (eresi_Addr) cur->addr, &off); if (off) snprintf(logbuf, BUFSIZ, " %c [%02u] " XFMT " <%s + " UFMT ">/n", (e2dbg_is_watchpoint(cur) ? 'W' : 'B'), cur->id, cur->addr, name, off); else snprintf(logbuf, BUFSIZ, " %c [%02u] " XFMT " <%s>/n", (e2dbg_is_watchpoint(cur) ? 'W' : 'B'), cur->id, cur->addr, name); e2dbg_output(logbuf); } hash_free_keys(keys); if (!index) e2dbg_output(" [*] No breakpoints/n"); e2dbg_output("/n"); break; /* Supply a new breakpoint */ case 1: if (!elfsh_is_runtime_mode()) PROFILER_ERR(__FILE__, __FUNCTION__, __LINE__, "Not in dynamic or debugger mode", -1); if (!str || !(*str)) PROFILER_ERR(__FILE__, __FUNCTION__, __LINE__, "Invalid argument", -1); /* Break on a supplied virtual address */ if (IS_VADDR(str)) { if (sscanf(str + 2, AFMT, &addr) != 1) PROFILER_ERR(__FILE__, __FUNCTION__, __LINE__, "Invalid virtual address requested", (-1)); } /* Resolve first a function name */ else { addr = e2dbg_breakpoint_find_addr(str); if (addr == 0) PROFILER_ERR(__FILE__, __FUNCTION__, __LINE__, "Requested symbol address unknown", -1); } /* Add the breakpoint */ ret = e2dbg_breakpoint_add(addr); if (ret < 0) PROFILER_ERR(__FILE__, __FUNCTION__, __LINE__, "Breakpoint insertion failed/n", (-1)); if (ret >= 0) { name = revm_resolve(world.curjob->curfile, addr, &off); if (!off) snprintf(logbuf, BUFSIZ - 1, " [*] Breakpoint added at <%s> (" XFMT ")/n/n", name, addr); else snprintf(logbuf, BUFSIZ - 1, " [*] Breakpoint added at <%s + " UFMT "> (" XFMT ")/n/n", name, off, addr); e2dbg_output(logbuf); } break; /* Wrong command syntax */ default: PROFILER_ERR(__FILE__, __FUNCTION__, __LINE__, "Wrong arg number", (-1)); }//.........这里部分代码省略.........
开发者ID:LucaBongiorni,项目名称:poly-engine,代码行数:101,
注:本文中的sscanf函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 C++ sscanf_P函数代码示例 C++ sscal_函数代码示例 |