本文整理汇总了C++中sscanf函数的典型用法代码示例。如果您正苦于以下问题:C++ sscanf函数的具体用法?C++ sscanf怎么用?C++ sscanf使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了sscanf函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: fin
bool 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;
}
示例2: init_from_conf_file
static void
init_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. */
示例3: network_connect
network_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;
}
示例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);
//.........这里部分代码省略.........
示例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;
}
示例6: main
int 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);
}
示例7: process_input
void 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) {
//.........这里部分代码省略.........
示例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);
//.........这里部分代码省略.........
示例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;
}
示例10: SetBoolArg
// FOR SYNCED MESSAGES
void 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) {
//.........这里部分代码省略.........
示例11: main
int 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);
}
示例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;
}
示例13: DBClientDataCallback
static 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);
//.........这里部分代码省略.........
示例14: WriteXTRNImage
static 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
//.........这里部分代码省略.........
示例15: clear
bool 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;
}