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

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

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

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

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

示例1: cairo_test_for_target

static cairo_test_status_tcairo_test_for_target (cairo_test_t			 *test,		       cairo_boilerplate_target_t	 *target,		       int				  dev_offset,		       cairo_bool_t                       similar){    cairo_test_status_t status;    cairo_surface_t *surface = NULL;    cairo_t *cr;    char *png_name, *ref_name, *diff_name, *offset_str;    cairo_test_status_t ret = CAIRO_TEST_SUCCESS;    cairo_content_t expected_content;    cairo_font_options_t *font_options;    const char *format;    /* Get the strings ready that we'll need. */    format = cairo_boilerplate_content_name (target->content);    if (dev_offset)	xasprintf (&offset_str, "-%d", dev_offset);    else	offset_str = strdup("");    xasprintf (&png_name, "%s-%s-%s%s%s%s",	       test->name,	       target->name,	       format,	       similar ? "-similar" : "",	       offset_str, CAIRO_TEST_PNG_SUFFIX);    ref_name = cairo_ref_name_for_test_target_format (test->name, target->name, format);    xasprintf (&diff_name, "%s-%s-%s%s%s%s",	       test->name,	       target->name,	       format,	       similar ? "-similar" : "",	       offset_str, CAIRO_TEST_DIFF_SUFFIX);    if (target->is_vector) {	int i;	for (i = 0; vector_ignored_tests[i] != NULL; i++)	    if (strcmp (test->name, vector_ignored_tests[i]) == 0) {		cairo_test_log ("Error: Skipping for vector target %s/n", target->name);		ret = CAIRO_TEST_UNTESTED;		goto UNWIND_STRINGS;	    }    }    if (ret == CAIRO_TEST_SUCCESS) {	/* Run the actual drawing code. */	if (test->width && test->height) {	    test->width += dev_offset;	    test->height += dev_offset;	}	surface = (target->create_surface) (test->name,					    target->content,					    test->width,					    test->height,					    CAIRO_BOILERPLATE_MODE_TEST,					    &target->closure);	if (test->width && test->height) {	    test->width -= dev_offset;	    test->height -= dev_offset;;	}    }    if (surface == NULL) {	cairo_test_log ("Error: Failed to set %s target/n", target->name);	ret = CAIRO_TEST_UNTESTED;	goto UNWIND_STRINGS;    }    /* Check that we created a surface of the expected type. */    if (cairo_surface_get_type (surface) != target->expected_type) {	cairo_test_log ("Error: Created surface is of type %d (expected %d)/n",			cairo_surface_get_type (surface), target->expected_type);	ret = CAIRO_TEST_FAILURE;	goto UNWIND_SURFACE;    }    /* Check that we created a surface of the expected content,     * (ignore the articifical     * CAIRO_TEST_CONTENT_COLOR_ALPHA_FLATTENED value).     */    expected_content = target->content;    if (expected_content == CAIRO_TEST_CONTENT_COLOR_ALPHA_FLATTENED)	expected_content = CAIRO_CONTENT_COLOR_ALPHA;    if (cairo_surface_get_content (surface) != expected_content) {	cairo_test_log ("Error: Created surface has content %d (expected %d)/n",			cairo_surface_get_content (surface), expected_content);	ret = CAIRO_TEST_FAILURE;	goto UNWIND_SURFACE;    }    cairo_surface_set_device_offset (surface, dev_offset, dev_offset);    cr = cairo_create (surface);//.........这里部分代码省略.........
开发者ID:Dirbaio,项目名称:libgdiplus,代码行数:101,


示例2: main

//.........这里部分代码省略.........			if ((s = getenv("LC_CTYPE")) == NULL || *s == '/0')				s = getenv("LANG");		}		if (s != NULL && (strcasestr(s, "UTF-8") != NULL ||		    strcasestr(s, "UTF8") != NULL))			flags |= CLIENT_UTF8;	}	environ_init(&global_environ);	for (var = environ; *var != NULL; var++)		environ_put(&global_environ, *var);	if (getcwd(tmp, sizeof tmp) != NULL)		environ_set(&global_environ, "PWD", tmp);	options_init(&global_options, NULL);	options_table_populate_tree(server_options_table, &global_options);	options_init(&global_s_options, NULL);	options_table_populate_tree(session_options_table, &global_s_options);	options_set_string(&global_s_options, "default-shell", "%s",	    getshell());	options_init(&global_w_options, NULL);	options_table_populate_tree(window_options_table, &global_w_options);	/* Enable UTF-8 if the first client is on UTF-8 terminal. */	if (flags & CLIENT_UTF8) {		options_set_number(&global_s_options, "status-utf8", 1);		options_set_number(&global_s_options, "mouse-utf8", 1);		options_set_number(&global_w_options, "utf8", 1);	}	/* Override keys to vi if VISUAL or EDITOR are set. */	if ((s = getenv("VISUAL")) != NULL || (s = getenv("EDITOR")) != NULL) {		if (strrchr(s, '/') != NULL)			s = strrchr(s, '/') + 1;		if (strstr(s, "vi") != NULL)			keys = MODEKEY_VI;		else			keys = MODEKEY_EMACS;		options_set_number(&global_s_options, "status-keys", keys);		options_set_number(&global_w_options, "mode-keys", keys);	}	/* Locate the configuration file. */	if (cfg_file == NULL) {		home = find_home();		if (home != NULL) {			xasprintf(&cfg_file, "%s/.tmux.conf", home);			if (access(cfg_file, R_OK) != 0 && errno == ENOENT) {				free(cfg_file);				cfg_file = NULL;			}		}	}	/* Get path from environment. */	s = getenv("TMUX");	if (s != NULL && sscanf(s, "%255[^,],%lld,%d", in, &pid, &session) == 3)		environ_path = xstrdup(in);	/*	 * Figure out the socket path. If specified on the command-line with -S	 * or -L, use it, otherwise try $TMUX or assume -L default.	 */	if (path == NULL) {		/* If no -L, use the environment. */		if (label == NULL) {			if (environ_path != NULL)				path = xstrdup(environ_path);			else				label = xstrdup("default");		}		/* -L or default set. */		if (label != NULL) {			if ((path = makesocketpath(label)) == NULL) {				fprintf(stderr, "can't create socket: %s/n",					strerror(errno));				exit(1);			}		}	}	free(label);	if (strlcpy(socket_path, path, sizeof socket_path) >= sizeof socket_path) {		fprintf(stderr, "socket path too long: %s/n", path);		exit(1);	}	free(path);#ifdef HAVE_SETPROCTITLE	/* Set process title. */	setproctitle("%s (%s)", __progname, socket_path);#endif	/* Pass control to the client. */	ev_base = osdep_event_init();	exit(client_main(argc, argv, flags));}
开发者ID:Ferada,项目名称:tmux,代码行数:101,


示例3: parse

static int parse(const char *boundary, char **argv){	char *line, *s, *p;	const char *type;	int boundary_len = strlen(boundary);	const char *delims = " ;/"/t/r/n";	const char *uniq;	int ntokens;	const char *tokens[32]; // 32 is enough	// prepare unique string pattern	uniq = xasprintf("%%llu.%u.%s", (unsigned)getpid(), safe_gethostname());//bb_info_msg("PARSE[%s]", uniq);	while ((line = xmalloc_fgets_str(stdin, "/r/n/r/n")) != NULL) {		// seek to start of MIME section		// N.B. to avoid false positives let us seek to the _last_ occurance		p = NULL;		s = line;		while ((s = strcasestr(s, "Content-Type:")) != NULL)			p = s++;		if (!p)			goto next;//bb_info_msg("L[%s]", p);		// split to tokens		// TODO: strip of comments which are of form: (comment-text)		ntokens = 0;		tokens[ntokens] = NULL;		for (s = strtok(p, delims); s; s = strtok(NULL, delims)) {			tokens[ntokens] = s;			if (ntokens < ARRAY_SIZE(tokens) - 1)				ntokens++;//bb_info_msg("L[%d][%s]", ntokens, s);		}		tokens[ntokens] = NULL;//bb_info_msg("N[%d]", ntokens);		// analyse tokens		type = find_token(tokens, "Content-Type:", "text/plain");//bb_info_msg("T[%s]", type);		if (0 == strncasecmp(type, "multipart/", 10)) {			if (0 == strcasecmp(type+10, "mixed")) {				parse(xfind_token(tokens, "boundary="), argv);			} else				bb_error_msg_and_die("no support of content type '%s'", type);		} else {			pid_t pid = pid;			int rc;			FILE *fp;			// fetch charset			const char *charset = find_token(tokens, "charset=", CONFIG_FEATURE_MIME_CHARSET);			// fetch encoding			const char *encoding = find_token(tokens, "Content-Transfer-Encoding:", "7bit");			// compose target filename			char *filename = (char *)find_token(tokens, "filename=", NULL);			if (!filename)				filename = xasprintf(uniq, monotonic_us());			else				filename = bb_get_last_path_component_strip(xstrdup(filename));			// start external helper, if any			if (opts & OPT_X) {				int fd[2];				xpipe(fd);				pid = vfork();				if (0 == pid) {					// child reads from fd[0]					close(fd[1]);					xmove_fd(fd[0], STDIN_FILENO);					xsetenv("CONTENT_TYPE", type);					xsetenv("CHARSET", charset);					xsetenv("ENCODING", encoding);					xsetenv("FILENAME", filename);					BB_EXECVP_or_die(argv);				}				// parent dumps to fd[1]				close(fd[0]);				fp = xfdopen_for_write(fd[1]);				signal(SIGPIPE, SIG_IGN); // ignore EPIPE			// or create a file for dump			} else {				char *fname = xasprintf("%s%s", *argv, filename);				fp = xfopen_for_write(fname);				free(fname);			}			// housekeeping			free(filename);			// dump to fp			if (0 == strcasecmp(encoding, "base64")) {				read_base64(stdin, fp, '-');			} else if (0 != strcasecmp(encoding, "7bit")				&& 0 != strcasecmp(encoding, "8bit")			) {				// quoted-printable, binary, user-defined are unsupported so far				bb_error_msg_and_die("no support of encoding '%s'", encoding);//.........这里部分代码省略.........
开发者ID:Claruarius,项目名称:stblinux-2.6.37,代码行数:101,


示例4: read_rsa_public_key

bool read_rsa_public_key(connection_t *c) {    FILE *fp;    char *fname;    char *key;    if(!c->rsa_key) {        c->rsa_key = RSA_new();//		RSA_blinding_on(c->rsa_key, NULL);    }    /* First, check for simple PublicKey statement */    if(get_config_string(lookup_config(c->config_tree, "PublicKey"), &key)) {        BN_hex2bn(&c->rsa_key->n, key);        BN_hex2bn(&c->rsa_key->e, "FFFF");        free(key);        return true;    }    /* Else, check for PublicKeyFile statement and read it */    if(get_config_string(lookup_config(c->config_tree, "PublicKeyFile"), &fname)) {        fp = fopen(fname, "r");        if(!fp) {            logger(LOG_ERR, "Error reading RSA public key file `%s': %s",                   fname, strerror(errno));            free(fname);            return false;        }        free(fname);        c->rsa_key = PEM_read_RSAPublicKey(fp, &c->rsa_key, NULL, NULL);        fclose(fp);        if(c->rsa_key)            return true;		/* Woohoo. */        /* If it fails, try PEM_read_RSA_PUBKEY. */        fp = fopen(fname, "r");        if(!fp) {            logger(LOG_ERR, "Error reading RSA public key file `%s': %s",                   fname, strerror(errno));            free(fname);            return false;        }        free(fname);        c->rsa_key = PEM_read_RSA_PUBKEY(fp, &c->rsa_key, NULL, NULL);        fclose(fp);        if(c->rsa_key) {//				RSA_blinding_on(c->rsa_key, NULL);            return true;        }        logger(LOG_ERR, "Reading RSA public key file `%s' failed: %s",               fname, strerror(errno));        return false;    }    /* Else, check if a harnessed public key is in the config file */    xasprintf(&fname, "%s/hosts/%s", confbase, c->name);    fp = fopen(fname, "r");    if(fp) {        c->rsa_key = PEM_read_RSAPublicKey(fp, &c->rsa_key, NULL, NULL);        fclose(fp);    }    free(fname);    if(c->rsa_key)        return true;    /* Try again with PEM_read_RSA_PUBKEY. */    xasprintf(&fname, "%s/hosts/%s", confbase, c->name);    fp = fopen(fname, "r");    if(fp) {        c->rsa_key = PEM_read_RSA_PUBKEY(fp, &c->rsa_key, NULL, NULL);//		RSA_blinding_on(c->rsa_key, NULL);        fclose(fp);    }    free(fname);    if(c->rsa_key)        return true;    logger(LOG_ERR, "No public key for %s specified!", c->name);    return false;}
开发者ID:Rumko,项目名称:tinc,代码行数:97,


示例5: load_public_identity_files

static voidload_public_identity_files(void){	char *filename, *cp, thishost[NI_MAXHOST];	char *pwdir = NULL, *pwname = NULL;	int i = 0;	Key *public;	struct passwd *pw;	u_int n_ids;	char *identity_files[SSH_MAX_IDENTITY_FILES];	Key *identity_keys[SSH_MAX_IDENTITY_FILES];#ifdef ENABLE_PKCS11	Key **keys;	int nkeys;#endif /* PKCS11 */	n_ids = 0;	bzero(identity_files, sizeof(identity_files));	bzero(identity_keys, sizeof(identity_keys));#ifdef ENABLE_PKCS11	if (options.pkcs11_provider != NULL &&	    options.num_identity_files < SSH_MAX_IDENTITY_FILES &&	    (pkcs11_init(!options.batch_mode) == 0) &&	    (nkeys = pkcs11_add_provider(options.pkcs11_provider, NULL,	    &keys)) > 0) {		for (i = 0; i < nkeys; i++) {			if (n_ids >= SSH_MAX_IDENTITY_FILES) {				key_free(keys[i]);				continue;			}			identity_keys[n_ids] = keys[i];			identity_files[n_ids] =			    xstrdup(options.pkcs11_provider); /* XXX */			n_ids++;		}		xfree(keys);	}#endif /* ENABLE_PKCS11 */	if ((pw = getpwuid(original_real_uid)) == NULL)		fatal("load_public_identity_files: getpwuid failed");	pwname = xstrdup(pw->pw_name);	pwdir = xstrdup(pw->pw_dir);	if (gethostname(thishost, sizeof(thishost)) == -1)		fatal("load_public_identity_files: gethostname: %s",		    strerror(errno));	for (i = 0; i < options.num_identity_files; i++) {		if (n_ids >= SSH_MAX_IDENTITY_FILES) {			xfree(options.identity_files[i]);			continue;		}		cp = tilde_expand_filename(options.identity_files[i],		    original_real_uid);		filename = percent_expand(cp, "d", pwdir,		    "u", pwname, "l", thishost, "h", host,		    "r", options.user, (char *)NULL);		xfree(cp);		public = key_load_public(filename, NULL);		debug("identity file %s type %d", filename,		    public ? public->type : -1);		xfree(options.identity_files[i]);		identity_files[n_ids] = filename;		identity_keys[n_ids] = public;		if (++n_ids >= SSH_MAX_IDENTITY_FILES)			continue;		/* Try to add the certificate variant too */		xasprintf(&cp, "%s-cert", filename);		public = key_load_public(cp, NULL);
开发者ID:ornarium,项目名称:freebsd,代码行数:70,


示例6: patch_main

int patch_main(int argc UNUSED_PARAM, char **argv){	struct stat saved_stat;	char *patch_line;	FILE *patch_file;	int patch_level;	int ret = 0;	char plus = '+';	xfunc_error_retval = 2;	{		const char *p = "-1";		const char *i = "-"; /* compat */		if (getopt32(argv, "p:i:R", &p, &i) & 4)			plus = '-';		patch_level = xatoi(p); /* can be negative! */		patch_file = xfopen_stdin(i);	}	patch_line = xmalloc_fgetline(patch_file);	while (patch_line) {		FILE *src_stream;		FILE *dst_stream;		//char *old_filename;		char *new_filename;		char *backup_filename;		unsigned src_cur_line = 1;		unsigned dst_cur_line = 0;		unsigned dst_beg_line;		unsigned bad_hunk_count = 0;		unsigned hunk_count = 0;		smallint copy_trailing_lines_flag = 0;		/* Skip everything upto the "---" marker		 * No need to parse the lines "Only in <dir>", and "diff <args>"		 */		do {			/* Extract the filename used before the patch was generated */			new_filename = extract_filename(patch_line, patch_level, "--- ");			// was old_filename above			patch_line = xmalloc_fgetline(patch_file);			if (!patch_line) goto quit;		} while (!new_filename);		free(new_filename); // "source" filename is irrelevant		new_filename = extract_filename(patch_line, patch_level, "+++ ");		if (!new_filename) {			bb_error_msg_and_die("invalid patch");		}		/* Get access rights from the file to be patched */		if (stat(new_filename, &saved_stat) != 0) {			char *slash = strrchr(new_filename, '/');			if (slash) {				/* Create leading directories */				*slash = '/0';				bb_make_directory(new_filename, -1, FILEUTILS_RECUR);				*slash = '/';			}			backup_filename = NULL;			src_stream = NULL;			saved_stat.st_mode = 0644;		} else {			backup_filename = xasprintf("%s.orig", new_filename);			xrename(new_filename, backup_filename);			src_stream = xfopen_for_read(backup_filename);		}		dst_stream = xfopen_for_write(new_filename);		fchmod(fileno(dst_stream), saved_stat.st_mode);		printf("patching file %s/n", new_filename);		/* Handle all hunks for this file */		patch_line = xmalloc_fgets(patch_file);		while (patch_line) {			unsigned count;			unsigned src_beg_line;			unsigned hunk_offset_start;			unsigned src_last_line = 1;			unsigned dst_last_line = 1;			if ((sscanf(patch_line, "@@ -%d,%d +%d,%d", &src_beg_line, &src_last_line, &dst_beg_line, &dst_last_line) < 3)			 && (sscanf(patch_line, "@@ -%d +%d,%d", &src_beg_line, &dst_beg_line, &dst_last_line) < 2)			) {				/* No more hunks for this file */				break;			}			if (plus != '+') {				/* reverse patch */				unsigned tmp = src_last_line;				src_last_line = dst_last_line;				dst_last_line = tmp;				tmp = src_beg_line;				src_beg_line = dst_beg_line;				dst_beg_line = tmp;			}			hunk_count++;			if (src_beg_line && dst_beg_line) {				/* Copy unmodified lines upto start of hunk *///.........这里部分代码省略.........
开发者ID:Jeanlst,项目名称:Onlive-Source-Backup,代码行数:101,


示例7: main

intmain (int argc, char **argv){  bool vmem_perfdata = false;  int c, status, err;  int shift = k_shift;  char *critical = NULL, *warning = NULL;  char *units = NULL;  char *status_msg;  char *perfdata_swap_msg, *perfdata_vmem_msg = NULL;  float percent_used = 0;  thresholds *my_threshold = NULL;  struct proc_sysmem *sysmem = NULL;  unsigned long kb_swap_cached;  unsigned long kb_swap_free;  unsigned long kb_swap_total;  unsigned long kb_swap_used;  struct proc_vmem *vmem = NULL;  unsigned long dpswpin, dpswpout;  unsigned long kb_swap_pageins[2];  unsigned long kb_swap_pageouts[2];  set_program_name (argv[0]);  while ((c = getopt_long (argc, argv, "sc:w:bkmg" GETOPT_HELP_VERSION_STRING,                           longopts, NULL)) != -1)    {      switch (c)        {        default:          usage (stderr);        case 's':          vmem_perfdata = true;          break;        case 'c':          critical = optarg;          break;        case 'w':          warning = optarg;          break;        case 'b': shift = b_shift; units = xstrdup ("B"); break;        case 'k': shift = k_shift; units = xstrdup ("kB"); break;        case 'm': shift = m_shift; units = xstrdup ("MB"); break;        case 'g': shift = g_shift; units = xstrdup ("GB"); break;        case_GETOPT_HELP_CHAR        case_GETOPT_VERSION_CHAR        }    }  status = set_thresholds (&my_threshold, warning, critical);  if (status == NP_RANGE_UNPARSEABLE)    usage (stderr);  /* output in kilobytes by default */  if (units == NULL)    units = xstrdup ("kB");  err = proc_sysmem_new (&sysmem);  if (err < 0)    plugin_error (STATE_UNKNOWN, err, "memory exhausted");  proc_sysmem_read (sysmem);  kb_swap_cached = proc_sysmem_get_swap_cached (sysmem);  kb_swap_free = proc_sysmem_get_swap_free (sysmem);  kb_swap_total = proc_sysmem_get_swap_total (sysmem);  kb_swap_used = proc_sysmem_get_swap_used (sysmem);  if (vmem_perfdata)    {      err = proc_vmem_new (&vmem);      if (err < 0)        plugin_error (STATE_UNKNOWN, err, "memory exhausted");      proc_vmem_read (vmem);      kb_swap_pageins[0] = proc_vmem_get_pswpin (vmem);      kb_swap_pageouts[0] = proc_vmem_get_pswpout (vmem);      sleep (1);      proc_vmem_read (vmem);      kb_swap_pageins[1] = proc_vmem_get_pswpin (vmem);      kb_swap_pageouts[1] = proc_vmem_get_pswpout (vmem);      dpswpin = kb_swap_pageins[1] - kb_swap_pageins[0];      dpswpout = kb_swap_pageouts[1] - kb_swap_pageouts[0];      perfdata_vmem_msg =	xasprintf (" swap_pageins/s=%lu swap_pageouts/s=%lu",		   dpswpin, dpswpout);    }  if (kb_swap_total != 0)    percent_used = (kb_swap_used * 100.0 / kb_swap_total);  status = get_status (percent_used, my_threshold);//.........这里部分代码省略.........
开发者ID:paulboot,项目名称:naemon_plugins,代码行数:101,


示例8: lpqr_main

//.........这里部分代码省略.........	hostname = safe_gethostname();	// no files given on command line? -> use stdin	if (!*argv)		*--argv = (char *)"-";	fdprintf(fd, "/x2" "%s/n", queue);	get_response_or_say_and_die(fd, "setting queue");	// process files	do {		unsigned cflen;		int dfd;		struct stat st;		char *c;		char *remote_filename;		char *controlfile;		// if data file is stdin, we need to dump it first		if (LONE_DASH(*argv)) {			strcpy(tempfile, "/tmp/lprXXXXXX");			dfd = xmkstemp(tempfile);			bb_copyfd_eof(STDIN_FILENO, dfd);			xlseek(dfd, 0, SEEK_SET);			*argv = (char*)bb_msg_standard_input;		} else {			dfd = xopen(*argv, O_RDONLY);		}		/* "The name ... should start with ASCII "cfA",		 * followed by a three digit job number, followed		 * by the host name which has constructed the file."		 * We supply 'c' or 'd' as needed for control/data file. */		remote_filename = xasprintf("fA%03u%s", job, hostname);		// create control file		// TODO: all lines but 2 last are constants! How we can use this fact?		controlfile = xasprintf(			"H" "%.32s/n" "P" "%.32s/n" /* H HOST, P USER */			"C" "%.32s/n" /* C CLASS - printed on banner page (if L cmd is also given) */			"J" "%.99s/n" /* J JOBNAME */			/* "class name for banner page and job name			 * for banner page commands must precede L command" */			"L" "%.32s/n" /* L USER - print banner page, with given user's name */			"M" "%.32s/n" /* M WHOM_TO_MAIL */			"l" "d%.31s/n" /* l DATA_FILE_NAME ("dfAxxx") */			, hostname, user			, printer_class /* can be "" */			, ((opts & LPR_J) ? job_title : *argv)			, (opts & LPR_h) ? user : ""			, (opts & LPR_m) ? user : ""			, remote_filename		);		// delete possible "/nX/n" patterns		c = controlfile;		cflen = (unsigned)strlen(controlfile);		while ((c = strchr(c, '/n')) != NULL) {			if (c[1] && c[2] == '/n') {				/* can't use strcpy, results are undefined */				memmove(c, c+2, cflen - (c-controlfile) - 1);				cflen -= 2;			} else {				c++;			}		}
开发者ID:915546302,项目名称:busybox-osx,代码行数:66,


示例9: main

int main(int argc, char **argv){/* should be 	int result = STATE_UNKNOWN; */	int return_code = STATE_UNKNOWN;	char *send_buffer=NULL;	char *output_message=NULL;	char *perfdata=NULL;	char *temp_string=NULL;	char *temp_string_perf=NULL;	char *description=NULL,*counter_unit = NULL;	char *minval = NULL, *maxval = NULL, *errcvt = NULL;	char *fds=NULL, *tds=NULL;	double total_disk_space=0;	double free_disk_space=0;	double percent_used_space=0;	double warning_used_space=0;	double critical_used_space=0;	double mem_commitLimit=0;	double mem_commitByte=0;	double fminval = 0, fmaxval = 0;	unsigned long utilization;	unsigned long uptime;	unsigned long age_in_minutes;	double counter_value = 0.0;	int offset=0;	int updays=0;	int uphours=0;	int upminutes=0;	int isPercent = FALSE;	int allRight = FALSE;	setlocale (LC_ALL, "");	bindtextdomain (PACKAGE, LOCALEDIR);	textdomain (PACKAGE);	/* Parse extra opts if any */	argv=np_extra_opts (&argc, argv, progname);	if(process_arguments(argc,argv) == ERROR)		usage4 (_("Could not parse arguments"));	/* initialize alarm signal handling */	signal(SIGALRM,socket_timeout_alarm_handler);	/* set socket timeout */	alarm(socket_timeout);	switch (vars_to_check) {	case CHECK_CLIENTVERSION:		xasprintf(&send_buffer, "%s&1", req_password);		fetch_data (server_address, server_port, send_buffer);		if (value_list != NULL && strcmp(recv_buffer, value_list) != 0) {			xasprintf (&output_message, _("Wrong client version - running: %s, required: %s"), recv_buffer, value_list);			return_code = STATE_WARNING;		} else {			xasprintf (&output_message, "%s", recv_buffer);			return_code = STATE_OK;		}		break;	case CHECK_CPULOAD:		if (value_list==NULL)			output_message = strdup (_("missing -l parameters"));		else if (strtoularray(lvalue_list,value_list,",")==FALSE)			output_message = strdup (_("wrong -l parameter."));		else {			/* -l parameters is present with only integers */			return_code=STATE_OK;			temp_string = strdup (_("CPU Load"));			temp_string_perf = strdup (" ");			/* loop until one of the parameters is wrong or not present */			while (lvalue_list[0+offset]> (unsigned long)0 &&						 lvalue_list[0+offset]<=(unsigned long)17280 &&						 lvalue_list[1+offset]> (unsigned long)0 &&						 lvalue_list[1+offset]<=(unsigned long)100 &&						 lvalue_list[2+offset]> (unsigned long)0 &&						 lvalue_list[2+offset]<=(unsigned long)100) {				/* Send request and retrieve data */				xasprintf(&send_buffer,"%s&2&%lu",req_password,lvalue_list[0+offset]);				fetch_data (server_address, server_port, send_buffer);				utilization=strtoul(recv_buffer,NULL,10);				/* Check if any of the request is in a warning or critical state */				if(utilization >= lvalue_list[2+offset])					return_code=STATE_CRITICAL;				else if(utilization >= lvalue_list[1+offset] && return_code<STATE_WARNING)					return_code=STATE_WARNING;				xasprintf(&output_message,_(" %lu%% (%lu min average)"), utilization, lvalue_list[0+offset]);				xasprintf(&temp_string,"%s%s",temp_string,output_message);				xasprintf(&perfdata,_(" '%lu min avg Load'=%lu%%;%lu;%lu;0;100"), lvalue_list[0+offset], utilization,//.........这里部分代码省略.........
开发者ID:abradley,项目名称:nagios-plugins,代码行数:101,


示例10: input_userauth_info_response

static voidinput_userauth_info_response(int type, u_int32_t seq, void *ctxt){	Authctxt *authctxt = ctxt;	KbdintAuthctxt *kbdintctxt;	int authenticated = 0, res;	u_int i, nresp;	char **response = NULL, *method;	if (authctxt == NULL)		fatal("input_userauth_info_response: no authctxt");	kbdintctxt = authctxt->kbdintctxt;	if (kbdintctxt == NULL || kbdintctxt->ctxt == NULL)		fatal("input_userauth_info_response: no kbdintctxt");	if (kbdintctxt->device == NULL)		fatal("input_userauth_info_response: no device");	authctxt->postponed = 0;	/* reset */	nresp = packet_get_int();	if (nresp != kbdintctxt->nreq)		fatal("input_userauth_info_response: wrong number of replies");	if (nresp > 100)		fatal("input_userauth_info_response: too many replies");	if (nresp > 0) {		response = xcalloc(nresp, sizeof(char *));		for (i = 0; i < nresp; i++)			response[i] = packet_get_string(NULL);	}	packet_check_eom();	res = kbdintctxt->device->respond(kbdintctxt->ctxt, nresp, response);	for (i = 0; i < nresp; i++) {		memset(response[i], 'r', strlen(response[i]));		xfree(response[i]);	}	if (response)		xfree(response);	switch (res) {	case 0:		/* Success! */		authenticated = authctxt->valid ? 1 : 0;		break;	case 1:		/* Authentication needs further interaction */		if (send_userauth_info_request(authctxt) == 1)			authctxt->postponed = 1;		break;	default:		/* Failure! */		break;	}	xasprintf(&method, "keyboard-interactive/%s", kbdintctxt->device->name);	if (!authctxt->postponed) {		if (authenticated) {			auth2_challenge_stop(authctxt);		} else {			/* start next device */			/* may set authctxt->postponed */			auth2_challenge_start(authctxt);		}	}	userauth_finish(authctxt, authenticated, method);	xfree(method);}
开发者ID:gosudream,项目名称:netbsd-src,代码行数:68,


示例11: passwd_main

int passwd_main(int argc UNUSED_PARAM, char **argv){	enum {		OPT_algo   = (1 << 0), /* -a - password algorithm */		OPT_lock   = (1 << 1), /* -l - lock account */		OPT_unlock = (1 << 2), /* -u - unlock account */		OPT_delete = (1 << 3), /* -d - delete password */		OPT_lud    = OPT_lock | OPT_unlock | OPT_delete,	};	unsigned opt;	int rc;	const char *opt_a = CONFIG_FEATURE_DEFAULT_PASSWD_ALGO;	const char *filename;	char *myname;	char *name;	char *newp;	struct passwd *pw;	uid_t myuid;	struct rlimit rlimit_fsize;	char c;#if ENABLE_FEATURE_SHADOWPASSWDS	/* Using _r function to avoid pulling in static buffers */	struct spwd spw;	char buffer[256];#endif	logmode = LOGMODE_BOTH;	openlog(applet_name, 0, LOG_AUTH);	opt = getopt32(argv, "a:lud", &opt_a);	//argc -= optind;	argv += optind;	myuid = getuid();	/* -l, -u, -d require root priv and username argument */	if ((opt & OPT_lud) && (myuid != 0 || !argv[0]))		bb_show_usage();	/* Will complain and die if username not found */	myname = xstrdup(xuid2uname(myuid));	name = argv[0] ? argv[0] : myname;	pw = xgetpwnam(name);	if (myuid != 0 && pw->pw_uid != myuid) {		/* LOGMODE_BOTH */		bb_error_msg_and_die("%s can't change password for %s", myname, name);	}#if ENABLE_FEATURE_SHADOWPASSWDS	{		/* getspnam_r may return 0 yet set result to NULL.		 * At least glibc 2.4 does this. Be extra paranoid here. */		struct spwd *result = NULL;		errno = 0;		if (getspnam_r(pw->pw_name, &spw, buffer, sizeof(buffer), &result) != 0		 || !result /* no error, but no record found either */		 || strcmp(result->sp_namp, pw->pw_name) != 0 /* paranoia */		) {			if (errno != ENOENT) {				/* LOGMODE_BOTH */				bb_perror_msg("no record of %s in %s, using %s",					name, bb_path_shadow_file,					bb_path_passwd_file);			}			/* else: /etc/shadow does not exist,			 * apparently we are on a shadow-less system,			 * no surprise there */		} else {			pw->pw_passwd = result->sp_pwdp;		}	}#endif	/* Decide what the new password will be */	newp = NULL;	c = pw->pw_passwd[0] - '!';	if (!(opt & OPT_lud)) {		if (myuid != 0 && !c) { /* passwd starts with '!' */			/* LOGMODE_BOTH */			bb_error_msg_and_die("can't change "					"locked password for %s", name);		}		printf("Changing password for %s/n", name);		newp = new_password(pw, myuid, opt_a);		if (!newp) {			logmode = LOGMODE_STDIO;			bb_error_msg_and_die("password for %s is unchanged", name);		}	} else if (opt & OPT_lock) {		if (!c)			goto skip; /* passwd starts with '!' */		newp = xasprintf("!%s", pw->pw_passwd);	} else if (opt & OPT_unlock) {		if (c)			goto skip; /* not '!' */		/* pw->pw_passwd points to static storage,		 * strdup'ing to avoid nasty surprizes */		newp = xstrdup(&pw->pw_passwd[1]);	} else if (opt & OPT_delete) {		newp = (char*)"";	}//.........这里部分代码省略.........
开发者ID:android-ide,项目名称:busybox,代码行数:101,


示例12: parse_options

static voidparse_options(int argc, char *argv[], struct shash *local_options){    enum {        OPT_DB = UCHAR_MAX + 1,        OPT_ONELINE,        OPT_NO_SYSLOG,        OPT_DRY_RUN,        OPT_PEER_CA_CERT,        OPT_LOCAL,        OPT_COMMANDS,        OPT_OPTIONS,        VLOG_OPTION_ENUMS,        TABLE_OPTION_ENUMS    };    static const struct option global_long_options[] = {        {"db", required_argument, NULL, OPT_DB},        {"no-syslog", no_argument, NULL, OPT_NO_SYSLOG},        {"dry-run", no_argument, NULL, OPT_DRY_RUN},        {"oneline", no_argument, NULL, OPT_ONELINE},        {"timeout", required_argument, NULL, 't'},        {"help", no_argument, NULL, 'h'},        {"commands", no_argument, NULL, OPT_COMMANDS},        {"options", no_argument, NULL, OPT_OPTIONS},        {"version", no_argument, NULL, 'V'},        VLOG_LONG_OPTIONS,        STREAM_SSL_LONG_OPTIONS,        TABLE_LONG_OPTIONS,        {NULL, 0, NULL, 0},    };    const int n_global_long_options = ARRAY_SIZE(global_long_options) - 1;    char *tmp, *short_options;    struct option *options;    size_t allocated_options;    size_t n_options;    size_t i;    tmp = ovs_cmdl_long_options_to_short_options(global_long_options);    short_options = xasprintf("+%s", tmp);    free(tmp);    /* We want to parse both global and command-specific options here, but     * getopt_long() isn't too convenient for the job.  We copy our global     * options into a dynamic array, then append all of the command-specific     * options. */    options = xmemdup(global_long_options, sizeof global_long_options);    allocated_options = ARRAY_SIZE(global_long_options);    n_options = n_global_long_options;    ctl_add_cmd_options(&options, &n_options, &allocated_options, OPT_LOCAL);    table_style.format = TF_LIST;    for (;;) {        int idx;        int c;        c = getopt_long(argc, argv, short_options, options, &idx);        if (c == -1) {            break;        }        switch (c) {        case OPT_DB:            db = optarg;            break;        case OPT_ONELINE:            oneline = true;            break;        case OPT_NO_SYSLOG:            vlog_set_levels(&VLM_sbctl, VLF_SYSLOG, VLL_WARN);            break;        case OPT_DRY_RUN:            dry_run = true;            break;        case OPT_LOCAL:            if (shash_find(local_options, options[idx].name)) {                ctl_fatal("'%s' option specified multiple times",                            options[idx].name);            }            shash_add_nocopy(local_options,                             xasprintf("--%s", options[idx].name),                             optarg ? xstrdup(optarg) : NULL);            break;        case 'h':            usage();        case OPT_COMMANDS:            ctl_print_commands();        case OPT_OPTIONS:            ctl_print_options(global_long_options);        case 'V':            ovs_print_version(0, 0);            printf("DB Schema %s/n", sbrec_get_db_version());//.........这里部分代码省略.........
开发者ID:hustcat,项目名称:ovs,代码行数:101,


示例13: osm_waypt_disp

static voidosm_waypt_disp(const waypoint *wpt){	char *buff;		xasprintf(&buff, "%s/01%f/01%f", (wpt->shortname) ? wpt->shortname : "",		wpt->latitude, wpt->longitude);	if (avltree_insert(waypoints, buff, (const void *) wpt)) {		int *id;				id = xmalloc(sizeof(*id));		*id = --node_id;		((waypoint *)(wpt))->extra_data = id;			gbfprintf(fout, "  <node id='%d' visible='true' lat='%f' lon='%f'", *id, wpt->latitude, wpt->longitude);		if (wpt->creation_time) {			char time_string[64];			xml_fill_in_time(time_string, wpt->creation_time, wpt->microseconds, XML_LONG_TIME);			gbfprintf(fout, " timestamp='%s'", time_string);		}		gbfprintf(fout, ">/n");		if (wpt->hdop) {			gbfprintf(fout, "    <tag k='gps:hdop' v='%f' />/n", wpt->hdop);		}		if (wpt->vdop) {			gbfprintf(fout, "    <tag k='gps:vdop' v='%f' />/n", wpt->vdop);		}		if (wpt->pdop) {			gbfprintf(fout, "    <tag k='gps:pdop' v='%f' />/n", wpt->pdop);		}		if (wpt->sat > 0) {			gbfprintf(fout, "    <tag k='gps:sat' v='%d' />/n", wpt->sat);		}		switch (wpt->fix) {			case fix_2d:				gbfprintf(fout, "    <tag k='gps:fix' v='2d' />/n");				break;			case fix_3d:				gbfprintf(fout, "    <tag k='gps:fix' v='3d' />/n");				break;			case fix_dgps:				gbfprintf(fout, "    <tag k='gps:fix' v='dgps' />/n");				break;			case fix_pps:				gbfprintf(fout, "    <tag k='gps:fix' v='pps' />/n");				break;			case fix_none:				gbfprintf(fout, "    <tag k='gps:fix' v='none' />/n");				break;			case fix_unknown:			default:				break;		}				if (strlen(created_by) !=0) {			gbfprintf(fout, "    <tag k='created_by' v='%s",created_by);			if (gpsbabel_time != 0)				if (strcmp("GPSBabel",created_by)==0)					gbfprintf(fout, "-%s", gpsbabel_version);			gbfprintf(fout, "'/>/n");		}				osm_write_tag("name", wpt->shortname);		osm_write_tag("note", (wpt->notes) ? wpt->notes : wpt->description);		if (wpt->icon_descr)			osm_disp_feature(wpt);		osm_write_opt_tag(opt_tagnd);		gbfprintf(fout, "  </node>/n");	}	xfree(buff);}
开发者ID:idaohang,项目名称:gpsbabel-flytec,代码行数:77,


示例14: osm_node_tag

static void osm_node_tag(const char *args, const char **attrv){	const char **avp = &attrv[0];	const char *key = "", *value = "";	char *str;	char ikey;	        while (*avp) {		if (strcmp(avp[0], "k") == 0)			key = avp[1];		else if (strcmp(avp[0], "v") == 0)			value = avp[1];		avp+=2;	}		str = osm_strip_html(value);		if (strcmp(key, "name") == 0) {		if (! wpt->shortname)			wpt->shortname = xstrdup(str);	}	else if (strcmp(key, "name:en") == 0) {		if (wpt->shortname)			xfree(wpt->shortname);		wpt->shortname = xstrdup(str);	}	else if ((ikey = osm_feature_ikey(key)) >= 0) {		wpt->icon_descr = osm_feature_symbol(ikey, value);		wpt->wpt_flags.icon_descr_is_dynamic = 1;	}	else if (strcmp(key, "note") == 0) {		if (wpt->notes) {			char *tmp;			xasprintf(&tmp, "%s; %s", wpt->notes, str);			xfree(wpt->notes);			wpt->notes = tmp;		}		else			wpt->notes = xstrdup(str);	}	else if (strcmp(key, "gps:hdop") == 0) {		wpt->hdop = atof(str);	}	else if (strcmp(key, "gps:vdop") == 0) {		wpt->vdop = atof(str);	}	else if (strcmp(key, "gps:pdop") == 0) {		wpt->pdop = atof(str);	}	else if (strcmp(key, "gps:sat") == 0) {		wpt->sat = atoi(str);	}	else if (strcmp(key, "gps:fix") == 0) {		if (strcmp(str, "2d") == 0) {			wpt->fix = fix_2d;		}		else if (strcmp(str, "3d") == 0) {			wpt->fix = fix_3d;		}		else if (strcmp(str, "dgps") == 0) {			wpt->fix = fix_dgps;		}		else if (strcmp(str, "pps") == 0) {			wpt->fix = fix_pps;		}		else if (strcmp(str, "none") == 0) {			wpt->fix = fix_none;		}	}	xfree(str);}
开发者ID:idaohang,项目名称:gpsbabel-flytec,代码行数:73,


示例15: cmd_load_buffer_exec

enum cmd_retvalcmd_load_buffer_exec(struct cmd *self, struct cmd_q *cmdq){	struct args	*args = self->args;	struct client	*c = cmdq->client;	struct session  *s;	FILE		*f;	const char	*path, *bufname, *cwd;	char		*pdata, *new_pdata, *cause, *file, resolved[PATH_MAX];	size_t		 psize;	int		 ch, error;	bufname = NULL;	if (args_has(args, 'b'))		bufname = args_get(args, 'b');	path = args->argv[0];	if (strcmp(path, "-") == 0) {		error = server_set_stdin_callback(c, cmd_load_buffer_callback,		    (void *)bufname, &cause);		if (error != 0) {			cmdq_error(cmdq, "%s: %s", path, cause);			free(cause);			return (CMD_RETURN_ERROR);		}		return (CMD_RETURN_WAIT);	}	if (c != NULL && c->session == NULL)		cwd = c->cwd;	else if ((s = cmd_find_current(cmdq)) != NULL)		cwd = s->cwd;	else		cwd = ".";	if (*path == '/')		file = xstrdup(path);	else		xasprintf(&file, "%s/%s", cwd, path);	if (realpath(file, resolved) == NULL &&	    strlcpy(resolved, file, sizeof resolved) >= sizeof resolved) {		cmdq_error(cmdq, "%s: %s", file, strerror(ENAMETOOLONG));		return (CMD_RETURN_ERROR);	}	f = fopen(resolved, "rb");	free(file);	if (f == NULL) {		cmdq_error(cmdq, "%s: %s", resolved, strerror(errno));		return (CMD_RETURN_ERROR);	}	pdata = NULL;	psize = 0;	while ((ch = getc(f)) != EOF) {		/* Do not let the server die due to memory exhaustion. */		if ((new_pdata = realloc(pdata, psize + 2)) == NULL) {			cmdq_error(cmdq, "realloc error: %s", strerror(errno));			goto error;		}		pdata = new_pdata;		pdata[psize++] = ch;	}	if (ferror(f)) {		cmdq_error(cmdq, "%s: read error", resolved);		goto error;	}	if (pdata != NULL)		pdata[psize] = '/0';	fclose(f);	if (paste_set(pdata, psize, bufname, &cause) != 0) {		cmdq_error(cmdq, "%s", cause);		free(pdata);		free(cause);		return (CMD_RETURN_ERROR);	}	return (CMD_RETURN_NORMAL);error:	free(pdata);	if (f != NULL)		fclose(f);	return (CMD_RETURN_ERROR);}
开发者ID:nbetm,项目名称:tmux,代码行数:86,


示例16: sama5d4_pmc_setup

//.........这里部分代码省略.........		goto err_free;	hw = at91_clk_register_plldiv(regmap, "plladivck", "pllack");	if (IS_ERR(hw))		goto err_free;	hw = at91_clk_register_utmi(regmap, NULL, "utmick", "mainck");	if (IS_ERR(hw))		goto err_free;	sama5d4_pmc->chws[PMC_UTMI] = hw;	parent_names[0] = slck_name;	parent_names[1] = "mainck";	parent_names[2] = "plladivck";	parent_names[3] = "utmick";	hw = at91_clk_register_master(regmap, "masterck", 4, parent_names,				      &at91sam9x5_master_layout,				      &mck_characteristics);	if (IS_ERR(hw))		goto err_free;	sama5d4_pmc->chws[PMC_MCK] = hw;	hw = at91_clk_register_h32mx(regmap, "h32mxck", "masterck");	if (IS_ERR(hw))		goto err_free;	sama5d4_pmc->chws[PMC_MCK2] = hw;	parent_names[0] = "plladivck";	parent_names[1] = "utmick";	hw = at91sam9x5_clk_register_usb(regmap, "usbck", parent_names, 2);	if (IS_ERR(hw))		goto err_free;	parent_names[0] = "plladivck";	parent_names[1] = "utmick";	hw = at91sam9x5_clk_register_smd(regmap, "smdclk", parent_names, 2);	if (IS_ERR(hw))		goto err_free;	parent_names[0] = slck_name;	parent_names[1] = "mainck";	parent_names[2] = "plladivck";	parent_names[3] = "utmick";	parent_names[4] = "mck";	for (i = 0; i < 3; i++) {		char *name;		name = xasprintf("prog%d", i);		hw = at91_clk_register_programmable(regmap, name,						    parent_names, 5, i,						    &at91sam9x5_programmable_layout);		if (IS_ERR(hw))			goto err_free;	}	for (i = 0; i < ARRAY_SIZE(sama5d4_systemck); i++) {		hw = at91_clk_register_system(regmap, sama5d4_systemck[i].n,					      sama5d4_systemck[i].p,					      sama5d4_systemck[i].id);		if (IS_ERR(hw))			goto err_free;		sama5d4_pmc->shws[sama5d4_systemck[i].id] = hw;	}	for (i = 0; i < ARRAY_SIZE(sama5d4_periphck); i++) {		hw = at91_clk_register_sam9x5_peripheral(regmap,							 sama5d4_periphck[i].n,							 "masterck",							 sama5d4_periphck[i].id,							 &range);		if (IS_ERR(hw))			goto err_free;		sama5d4_pmc->phws[sama5d4_periphck[i].id] = hw;	}	for (i = 0; i < ARRAY_SIZE(sama5d4_periph32ck); i++) {		hw = at91_clk_register_sam9x5_peripheral(regmap,							 sama5d4_periph32ck[i].n,							 "h32mxck",							 sama5d4_periph32ck[i].id,							 &range);		if (IS_ERR(hw))			goto err_free;		sama5d4_pmc->phws[sama5d4_periph32ck[i].id] = hw;	}	of_clk_add_provider(np, of_clk_hw_pmc_get, sama5d4_pmc);	return;err_free:	pmc_data_free(sama5d4_pmc);}
开发者ID:masahir0y,项目名称:barebox-yamada,代码行数:101,


示例17: parse_nfo

voidparse_nfo(const char *path, metadata_t *m){	FILE *nfo;	char buf[65536];	struct NameValueParserData xml;	struct stat file;	size_t nread;	char *val, *val2;	if( stat(path, &file) != 0 ||	    file.st_size > 65536 )	{		DPRINTF(E_INFO, L_METADATA, "Not parsing very large .nfo file %s/n", path);		return;	}	DPRINTF(E_DEBUG, L_METADATA, "Parsing .nfo file: %s/n", path);	nfo = fopen(path, "r");	if( !nfo )		return;	nread = fread(&buf, 1, sizeof(buf), nfo);		ParseNameValue(buf, nread, &xml, 0);	//printf("/ttype: %s/n", GetValueFromNameValueList(&xml, "rootElement"));	val = GetValueFromNameValueList(&xml, "title");	if( val )	{		char *esc_tag, *title;		val2 = GetValueFromNameValueList(&xml, "episodetitle");		if( val2 )			xasprintf(&title, "%s - %s", val, val2);		else			title = strdup(val);		esc_tag = unescape_tag(title, 1);		m->title = escape_tag(esc_tag, 1);		free(esc_tag);		free(title);	}	val = GetValueFromNameValueList(&xml, "plot");	if( val ) {		char *esc_tag = unescape_tag(val, 1);		m->comment = escape_tag(esc_tag, 1);		free(esc_tag);	}	val = GetValueFromNameValueList(&xml, "capturedate");	if( val ) {		char *esc_tag = unescape_tag(val, 1);		m->date = escape_tag(esc_tag, 1);		free(esc_tag);	}	val = GetValueFromNameValueList(&xml, "genre");	if( val )	{		free(m->genre);		char *esc_tag = unescape_tag(val, 1);		m->genre = escape_tag(esc_tag, 1);		free(esc_tag);	}	val = GetValueFromNameValueList(&xml, "mime");	if( val )	{		free(m->mime);		char *esc_tag = unescape_tag(val, 1);		m->mime = escape_tag(esc_tag, 1);		free(esc_tag);	}	ClearNameValueList(&xml);	fclose(nfo);}
开发者ID:alcoheca,项目名称:minidlna,代码行数:75,


示例18: ssh_connect

intssh_connect (char *haddr, int hport, char *remote_version, char *remote_protocol){	int sd;	int result;	char *output = NULL;	char *buffer = NULL;	char *ssh_proto = NULL;	char *ssh_server = NULL;	static char *rev_no = VERSION;	struct timeval tv;	double elapsed_time;	gettimeofday(&tv, NULL);	result = my_tcp_connect (haddr, hport, &sd);	if (result != STATE_OK)		return result;	output = (char *) malloc (BUFF_SZ + 1);	memset (output, 0, BUFF_SZ + 1);	recv (sd, output, BUFF_SZ, 0);	if (strncmp (output, "SSH", 3)) {		printf (_("Server answer: %s"), output);		close(sd);		exit (STATE_CRITICAL);	}	else {		strip (output);		if (verbose)			printf ("%s/n", output);		ssh_proto = output + 4;		ssh_server = ssh_proto + strspn (ssh_proto, "-0123456789. ");		ssh_proto[strspn (ssh_proto, "0123456789. ")] = 0;		xasprintf (&buffer, "SSH-%s-check_ssh_%s/r/n", ssh_proto, rev_no);		send (sd, buffer, strlen (buffer), MSG_DONTWAIT);		if (verbose)			printf ("%s/n", buffer);		if (remote_version && strcmp(remote_version, ssh_server)) {			printf				(_("SSH WARNING - %s (protocol %s) version mismatch, expected '%s'/n"),				 ssh_server, ssh_proto, remote_version);			close(sd);			exit (STATE_WARNING);		}		if (remote_protocol && strcmp(remote_protocol, ssh_proto)) {			printf				(_("SSH WARNING - %s (protocol %s) protocol version mismatch, expected '%s'/n"),				 ssh_server, ssh_proto, remote_protocol);			close(sd);			exit (STATE_WARNING);		}		elapsed_time = (double)deltime(tv) / 1.0e6;		printf			(_("SSH OK - %s (protocol %s) | %s/n"),			 ssh_server, ssh_proto, fperfdata("time", elapsed_time, "s",			 FALSE, 0, FALSE, 0, TRUE, 0, TRUE, (int)socket_timeout));		close(sd);		exit (STATE_OK);	}}
开发者ID:Freeaqingme,项目名称:monitoring-plugins,代码行数:67,


示例19: GetAudioMetadata

int64_tGetAudioMetadata(const char *path, char *name){	char type[4];	static char lang[6] = { '/0' };	struct stat file;	int64_t ret;	char *esc_tag;	int i;	int64_t album_art = 0;	struct song_metadata song;	metadata_t m;	uint32_t free_flags = FLAG_MIME|FLAG_DURATION|FLAG_DLNA_PN|FLAG_DATE;	memset(&m, '/0', sizeof(metadata_t));	if ( stat(path, &file) != 0 )		return 0;	strip_ext(name);	if( ends_with(path, ".mp3") )	{		strcpy(type, "mp3");		m.mime = strdup("audio/mpeg");	}	else if( ends_with(path, ".m4a") || ends_with(path, ".mp4") ||	         ends_with(path, ".aac") || ends_with(path, ".m4p") )	{		strcpy(type, "aac");		m.mime = strdup("audio/mp4");	}	else if( ends_with(path, ".3gp") )	{		strcpy(type, "aac");		m.mime = strdup("audio/3gpp");	}	else if( ends_with(path, ".wma") || ends_with(path, ".asf") )	{		strcpy(type, "asf");		m.mime = strdup("audio/x-ms-wma");	}	else if( ends_with(path, ".flac") || ends_with(path, ".fla") || ends_with(path, ".flc") )	{		strcpy(type, "flc");		m.mime = strdup("audio/x-flac");	}	else if( ends_with(path, ".wav") )	{		strcpy(type, "wav");		m.mime = strdup("audio/x-wav");	}	else if( ends_with(path, ".ogg") || ends_with(path, ".oga") )	{		strcpy(type, "ogg");		m.mime = strdup("audio/ogg");	}	else if( ends_with(path, ".pcm") )	{		strcpy(type, "pcm");		m.mime = strdup("audio/L16");	}	else	{		DPRINTF(E_WARN, L_METADATA, "Unhandled file extension on %s/n", path);		return 0;	}	if( !(*lang) )	{		if( !getenv("LANG") )			strcpy(lang, "en_US");		else			strncpyt(lang, getenv("LANG"), sizeof(lang));	}	if( readtags((char *)path, &song, &file, lang, type) != 0 )	{		DPRINTF(E_WARN, L_METADATA, "Cannot extract tags from %s!/n", path);        	freetags(&song);		free_metadata(&m, free_flags);		return 0;	}	if( song.dlna_pn )		m.dlna_pn = strdup(song.dlna_pn);	if( song.year )		xasprintf(&m.date, "%04d-01-01", song.year);	xasprintf(&m.duration, "%d:%02d:%02d.%03d",	                      (song.song_length/3600000),	                      (song.song_length/60000%60),	                      (song.song_length/1000%60),	                      (song.song_length%1000));	if( song.title && *song.title )	{		m.title = trim(song.title);		if( (esc_tag = escape_tag(m.title, 0)) )		{			free_flags |= FLAG_TITLE;			m.title = esc_tag;		}	}//.........这里部分代码省略.........
开发者ID:alcoheca,项目名称:minidlna,代码行数:101,


示例20: sockets

/*  Configure node_t myself and set up the local sockets (listen only)*/bool setup_myself(void) {    config_t *cfg;    subnet_t *subnet;    char *name, *hostname, *mode, *afname, *cipher, *digest;    char *fname = NULL;    char *address = NULL;    char *envp[5];    struct addrinfo *ai, *aip, hint = {0};    bool choice;    int i, err;    int replaywin_int;    myself = new_node();    myself->connection = new_connection();    myself->hostname = xstrdup("MYSELF");    myself->connection->hostname = xstrdup("MYSELF");    myself->connection->options = 0;    myself->connection->protocol_version = PROT_CURRENT;    if(!get_config_string(lookup_config(config_tree, "Name"), &name)) {	/* Not acceptable */        logger(LOG_ERR, "Name for tinc daemon required!");        return false;    }    if(!check_id(name)) {        logger(LOG_ERR, "Invalid name for myself!");        free(name);        return false;    }    myself->name = name;    myself->connection->name = xstrdup(name);    xasprintf(&fname, "%s/hosts/%s", confbase, name);    read_config_options(config_tree, name);    read_config_file(config_tree, fname);    free(fname);    if(!read_rsa_private_key())        return false;    if(!get_config_string(lookup_config(config_tree, "Port"), &myport))        myport = xstrdup("655");    if(!atoi(myport)) {        struct addrinfo *ai = str2addrinfo("localhost", myport, SOCK_DGRAM);        sockaddr_t sa;        if(!ai || !ai->ai_addr)            return false;        free(myport);        memcpy(&sa, ai->ai_addr, ai->ai_addrlen);        sockaddr2str(&sa, NULL, &myport);    }    /* Read in all the subnets specified in the host configuration file */    cfg = lookup_config(config_tree, "Subnet");    while(cfg) {        if(!get_config_subnet(cfg, &subnet))            return false;        subnet_add(myself, subnet);        cfg = lookup_config_next(config_tree, cfg);    }    /* Check some options */    if(get_config_bool(lookup_config(config_tree, "IndirectData"), &choice) && choice)        myself->options |= OPTION_INDIRECT;    if(get_config_bool(lookup_config(config_tree, "TCPOnly"), &choice) && choice)        myself->options |= OPTION_TCPONLY;    if(myself->options & OPTION_TCPONLY)        myself->options |= OPTION_INDIRECT;    get_config_bool(lookup_config(config_tree, "DirectOnly"), &directonly);    get_config_bool(lookup_config(config_tree, "StrictSubnets"), &strictsubnets);    get_config_bool(lookup_config(config_tree, "TunnelServer"), &tunnelserver);    strictsubnets |= tunnelserver;    if(get_config_string(lookup_config(config_tree, "Mode"), &mode)) {        if(!strcasecmp(mode, "router"))            routing_mode = RMODE_ROUTER;        else if(!strcasecmp(mode, "switch"))            routing_mode = RMODE_SWITCH;        else if(!strcasecmp(mode, "hub"))            routing_mode = RMODE_HUB;        else {            logger(LOG_ERR, "Invalid routing mode!");            return false;        }        free(mode);    }//.........这里部分代码省略.........
开发者ID:Rumko,项目名称:tinc,代码行数:101,


示例21: GetImageMetadata

//.........这里部分代码省略.........	}	//DEBUG DPRINTF(E_DEBUG, L_METADATA, " * model: %s/n", model);	e = exif_content_get_entry(ed->ifd[EXIF_IFD_0], EXIF_TAG_ORIENTATION);	if( e )	{		switch( exif_get_short(e->data, exif_data_get_byte_order(ed)) )		{		case 3:			m.rotation = 180;			break;		case 6:			m.rotation = 90;			break;		case 8:			m.rotation = 270;			break;		default:			m.rotation = 0;			break;		}	}	if( ed->size )	{		/* We might need to verify that the thumbnail is 160x160 or smaller */		if( ed->size > 12000 )		{			imsrc = image_new_from_jpeg(NULL, 0, ed->data, ed->size, 1, ROTATE_NONE);			if( imsrc )			{ 				if( (imsrc->width <= 160) && (imsrc->height <= 160) )					thumb = 1;				image_free(imsrc);			}		}		else			thumb = 1;	}	//DEBUG DPRINTF(E_DEBUG, L_METADATA, " * thumbnail: %d/n", thumb);	exif_data_unref(ed);no_exifdata:	/* If SOF parsing fails, then fall through to reading the JPEG data with libjpeg to get the resolution */	if( image_get_jpeg_resolution(path, &width, &height) != 0 || !width || !height )	{		infile = fopen(path, "r");		if( infile )		{			cinfo.err = jpeg_std_error(&jerr);			jerr.error_exit = libjpeg_error_handler;			jpeg_create_decompress(&cinfo);			if( setjmp(setjmp_buffer) )				goto error;			jpeg_stdio_src(&cinfo, infile);			jpeg_read_header(&cinfo, TRUE);			jpeg_start_decompress(&cinfo);			width = cinfo.output_width;			height = cinfo.output_height;			error:			jpeg_destroy_decompress(&cinfo);			fclose(infile);		}	}	//DEBUG DPRINTF(E_DEBUG, L_METADATA, " * resolution: %dx%d/n", width, height);	if( !width || !height )	{		free_metadata(&m, free_flags);		return 0;	}	if( width <= 640 && height <= 480 )		m.dlna_pn = strdup("JPEG_SM");	else if( width <= 1024 && height <= 768 )		m.dlna_pn = strdup("JPEG_MED");	else if( (width <= 4096 && height <= 4096) || !GETFLAG(DLNA_STRICT_MASK) )		m.dlna_pn = strdup("JPEG_LRG");	xasprintf(&m.resolution, "%dx%d", width, height);	ret = sql_exec(db, "INSERT into DETAILS"	                   " (PATH, TITLE, SIZE, TIMESTAMP, DATE, RESOLUTION,"	                    " ROTATION, THUMBNAIL, CREATOR, DLNA_PN, MIME) "	                   "VALUES"	                   " (%Q, '%q', %lld, %lld, %Q, %Q, %u, %d, %Q, %Q, %Q);",	                   path, name, (long long)file.st_size, (long long)file.st_mtime, m.date,	                   m.resolution, m.rotation, thumb, m.creator, m.dlna_pn, m.mime);	if( ret != SQLITE_OK )	{		DPRINTF(E_ERROR, L_METADATA, "Error inserting details for '%s'!/n", path);		ret = 0;	}	else	{		ret = sqlite3_last_insert_rowid(db);	}	free_metadata(&m, free_flags);	return ret;}
开发者ID:alcoheca,项目名称:minidlna,代码行数:101,


示例22: main

int main (int argc, char *argv[]){    flux_t h = NULL;    int ch;    char *cmd;    func_t *f;    opt_t opt = {        .fanout = 1024,        .nodeset = NULL,    };    log_init ("flux-module");    if (argc < 2)        usage ();    cmd = argv[1];    argc--;    argv++;    while ((ch = getopt_long (argc, argv, OPTIONS, longopts, NULL)) != -1) {        switch (ch) {            case 'h': /* --help */                usage ();                break;            case 'r': /* --rank=[nodeset|all] */                if (opt.nodeset)                    free (opt.nodeset);                opt.nodeset = xstrdup (optarg);                break;            case 'd': /* --direct */                opt.direct = true;                break;            case 'f': /* --fanout */                opt.fanout = strtoul (optarg, NULL, 10);                break;            default:                usage ();                break;        }    }    opt.argc = argc - optind;    opt.argv = argv + optind;    if (!(f = func_lookup (cmd)))        msg_exit ("unknown function '%s'", cmd);    if (strcmp (cmd, "info") != 0) {        if (!(h = flux_open (NULL, 0)))            err_exit ("flux_open");        if (!opt.nodeset) {            opt.nodeset = xasprintf ("%d", flux_rank (h));        } else if (!strcmp (opt.nodeset, "all") && flux_size (h) == 1) {            free (opt.nodeset);            opt.nodeset= xasprintf ("%d", flux_rank (h));        } else if (!strcmp (opt.nodeset, "all")) {            free (opt.nodeset);            opt.nodeset = xasprintf ("[0-%d]", flux_size (h) - 1);        }    }    f->fun (h, opt);    if (opt.nodeset)        free (opt.nodeset);    if (h)        flux_close (h);    log_fini ();    return 0;}char *sha1 (const char *path){    zfile_t *zf = zfile_new (NULL, path);    char *digest = NULL;    if (zf)        digest = xstrdup (zfile_digest (zf));    zfile_destroy (&zf);    return digest;}
开发者ID:dinesh121991,项目名称:flux-core,代码行数:80,


示例23: GetVideoMetadata

//.........这里部分代码省略.........					memcpy(&data, ac->extradata, 1);					aac_type = data >> 3;				}				switch( aac_type )				{					/* AAC Low Complexity variants */					case AAC_LC:					case AAC_LC_ER:						if( ac->sample_rate < 8000 ||						    ac->sample_rate > 48000 )						{							DPRINTF(E_DEBUG, L_METADATA, "Unsupported AAC: sample rate is not 8000 < %d < 48000/n",								ac->sample_rate);							break;						}						/* AAC @ Level 1/2 */						if( ac->channels <= 2 &&						    ac->bit_rate <= 576000 )							audio_profile = PROFILE_AUDIO_AAC;						else if( ac->channels <= 6 &&							 ac->bit_rate <= 1440000 )							audio_profile = PROFILE_AUDIO_AAC_MULT5;						else							DPRINTF(E_DEBUG, L_METADATA, "Unhandled AAC: %d channels, %d bitrate/n",								ac->channels,								ac->bit_rate);						break;					default:						DPRINTF(E_DEBUG, L_METADATA, "Unhandled AAC type [%d]/n", aac_type);						break;				}				break;			case AV_CODEC_ID_AC3:			case AV_CODEC_ID_DTS:				audio_profile = PROFILE_AUDIO_AC3;				break;			case AV_CODEC_ID_WMAV1:			case AV_CODEC_ID_WMAV2:				/* WMA Baseline: stereo, up to 48 KHz, up to 192,999 bps */				if ( ac->bit_rate <= 193000 )					audio_profile = PROFILE_AUDIO_WMA_BASE;				/* WMA Full: stereo, up to 48 KHz, up to 385 Kbps */				else if ( ac->bit_rate <= 385000 )					audio_profile = PROFILE_AUDIO_WMA_FULL;				break;			case AV_CODEC_ID_WMAPRO:				audio_profile = PROFILE_AUDIO_WMA_PRO;				break;			case AV_CODEC_ID_MP2:				audio_profile = PROFILE_AUDIO_MP2;				break;			case AV_CODEC_ID_AMR_NB:				audio_profile = PROFILE_AUDIO_AMR;				break;			default:				if( (ac->codec_id >= AV_CODEC_ID_PCM_S16LE) &&				    (ac->codec_id < AV_CODEC_ID_ADPCM_IMA_QT) )					audio_profile = PROFILE_AUDIO_PCM;				else					DPRINTF(E_DEBUG, L_METADATA, "Unhandled audio codec [0x%X]/n", ac->codec_id);				break;		}		m.frequency = ac->sample_rate;		m.channels = ac->channels;	}	if( vc )	{		int off;		int duration, hours, min, sec, ms;		ts_timestamp_t ts_timestamp = NONE;		DPRINTF(E_DEBUG, L_METADATA, "Container: '%s' [%s]/n", ctx->iformat->name, basepath);		xasprintf(&m.resolution, "%dx%d", vc->width, vc->height);		if( ctx->bit_rate > 8 )			m.bitrate = ctx->bit_rate / 8;		if( ctx->duration > 0 ) {			duration = (int)(ctx->duration / AV_TIME_BASE);			hours = (int)(duration / 3600);			min = (int)(duration / 60 % 60);			sec = (int)(duration % 60);			ms = (int)(ctx->duration / (AV_TIME_BASE/1000) % 1000);			xasprintf(&m.duration, "%d:%02d:%02d.%03d", hours, min, sec, ms);		}		/* NOTE: The DLNA spec only provides for ASF (WMV), TS, PS, and MP4 containers.		 * Skip DLNA parsing for everything else. */		if( strcmp(ctx->iformat->name, "avi") == 0 )		{			xasprintf(&m.mime, "video/x-msvideo");			if( vc->codec_id == AV_CODEC_ID_MPEG4 )			{        			fourcc[0] = vc->codec_tag     & 0xff;			        fourcc[1] = vc->codec_tag>>8  & 0xff;		        	fourcc[2] = vc->codec_tag>>16 & 0xff;			        fourcc[3] = vc->codec_tag>>24 & 0xff;				if( memcmp(fourcc, "XVID", 4) == 0 ||				    memcmp(fourcc, "DX50", 4) == 0 ||				    memcmp(fourcc, "DIVX", 4) == 0 )					xasprintf(&m.creator, "DiVX");			}		}
开发者ID:alcoheca,项目名称:minidlna,代码行数:101,


示例24: popmaildir_main

int popmaildir_main(int argc UNUSED_PARAM, char **argv){	char *buf;	unsigned nmsg;	char *hostname;	pid_t pid;	const char *retr;#if ENABLE_FEATURE_POPMAILDIR_DELIVERY	const char *delivery;#endif	unsigned opt_nlines = 0;	enum {		OPT_b = 1 << 0,		// -b binary mode. Ignored		OPT_d = 1 << 1,		// -d,-dd,-ddd debug. Ignored		OPT_m = 1 << 2,		// -m show used memory. Ignored		OPT_V = 1 << 3,		// -V version. Ignored		OPT_c = 1 << 4,		// -c use tcpclient. Ignored		OPT_a = 1 << 5,		// -a use APOP protocol		OPT_s = 1 << 6,		// -s skip authorization		OPT_T = 1 << 7,		// -T get messages with TOP instead with RETR		OPT_k = 1 << 8,		// -k keep retrieved messages on the server		OPT_t = 1 << 9,		// -t90 set timeout to 90 sec		OPT_R = 1 << 10,	// -R20000 remove old messages on the server >= 20000 bytes (requires -k). Ignored		OPT_Z = 1 << 11,	// -Z11-23 remove messages from 11 to 23 (dangerous). Ignored		OPT_L = 1 << 12,	// -L50000 not retrieve new messages >= 50000 bytes. Ignored		OPT_H = 1 << 13,	// -H30 type first 30 lines of a message; (-L12000 -H30). Ignored		OPT_M = 1 << 14,	// -M/"program arg1 arg2 .../"; deliver by program. Treated like -F		OPT_F = 1 << 15,	// -F/"program arg1 arg2 .../"; filter by program. Treated like -M	};	// init global variables	INIT_G();	// parse options	opts = getopt32(argv, "^"		"bdmVcasTkt:+" "R:+Z:L:+H:+" IF_FEATURE_POPMAILDIR_DELIVERY("M:F:")		"/0" "-1:dd",		&timeout, NULL, NULL, NULL, &opt_nlines		IF_FEATURE_POPMAILDIR_DELIVERY(, &delivery, &delivery) // we treat -M and -F the same	);	//argc -= optind;	argv += optind;	// get auth info	if (!(opts & OPT_s))		get_cred_or_die(STDIN_FILENO);	// goto maildir	xchdir(*argv++);	// launch connect helper, if any	if (*argv)		launch_helper((const char **)argv);	// get server greeting	pop3_checkr(NULL, NULL, &buf);	// authenticate (if no -s given)	if (!(opts & OPT_s)) {		// server supports APOP and we want it?		if ('<' == buf[0] && (opts & OPT_a)) {			union { // save a bit of stack				md5_ctx_t ctx;				char hex[16 * 2 + 1];			} md5;			uint32_t res[16 / 4];			char *s = strchr(buf, '>');			if (s)				s[1] = '/0';			// get md5 sum of "<stamp>password" string			md5_begin(&md5.ctx);			md5_hash(&md5.ctx, buf, strlen(buf));			md5_hash(&md5.ctx, G.pass, strlen(G.pass));			md5_end(&md5.ctx, res);			*bin2hex(md5.hex, (char*)res, 16) = '/0';			// APOP			s = xasprintf("%s %s", G.user, md5.hex);			pop3_check("APOP %s", s);			free(s);			free(buf);		// server ignores APOP -> use simple text authentication		} else {			// USER			pop3_check("USER %s", G.user);			// PASS			pop3_check("PASS %s", G.pass);		}	}	// get mailbox statistics	pop3_checkr("STAT", NULL, &buf);	// prepare message filename suffix	hostname = safe_gethostname();	pid = getpid();	// get messages counter	// NOTE: we don't use xatou(buf) since buf is "nmsg nbytes"//.........这里部分代码省略.........
开发者ID:nawawi,项目名称:busybox,代码行数:101,


示例25: append_ext

char* FAST_FUNC append_ext(char *filename, const char *expected_ext){	return xasprintf("%s.%s", filename, expected_ext);}
开发者ID:Dialga,项目名称:busybox-w32,代码行数:4,


示例26: makemime_main

int makemime_main(int argc UNUSED_PARAM, char **argv){	llist_t *opt_headers = NULL, *l;	const char *opt_output;#define boundary opt_output	enum {		OPT_c = 1 << 0,         // Content-Type:		OPT_e = 1 << 1,         // Content-Transfer-Encoding. Ignored. Assumed base64		OPT_o = 1 << 2,         // output to		OPT_C = 1 << 3,         // charset		OPT_N = 1 << 4,         // COMPAT		OPT_a = 1 << 5,         // additional headers		OPT_m = 1 << 6,         // COMPAT		OPT_j = 1 << 7,         // COMPAT	};	INIT_G();	// parse options	opt_complementary = "a::";	opts = getopt32(argv,		"c:e:o:C:N:a:m:j:",		&G.content_type, NULL, &opt_output, &G.opt_charset, NULL, &opt_headers, NULL, NULL	);	//argc -= optind;	argv += optind;	// respect -o output	if (opts & OPT_o)		freopen(opt_output, "w", stdout);	// no files given on command line? -> use stdin	if (!*argv)		*--argv = (char *)"-";	// put additional headers	for (l = opt_headers; l; l = l->link)		puts(l->data);	// make a random string -- it will delimit message parts	srand(monotonic_us());	boundary = xasprintf("%u-%u-%u",			(unsigned)rand(), (unsigned)rand(), (unsigned)rand());	// put multipart header	printf(		"Mime-Version: 1.0/n"		"Content-Type: multipart/mixed; boundary=/"%s/"/n"		, boundary	);	// put attachments	while (*argv) {		printf(			"/n--%s/n"			"Content-Type: %s; charset=%s/n"			"Content-Disposition: inline; filename=/"%s/"/n"			"Content-Transfer-Encoding: base64/n"			, boundary			, G.content_type			, G.opt_charset			, bb_get_last_path_component_strip(*argv)		);		encode_base64(*argv++, (const char *)stdin, "");	}	// put multipart footer	printf("/n--%s--/n" "/n", boundary);	return EXIT_SUCCESS;#undef boundary}
开发者ID:Claruarius,项目名称:stblinux-2.6.37,代码行数:73,


示例27: parse_options

static voidparse_options(struct datapath *dp, int argc, char *argv[]){    enum {        OPT_MFR_DESC = UCHAR_MAX + 1,        OPT_HW_DESC,        OPT_SW_DESC,        OPT_DP_DESC,        OPT_SERIAL_NUM,        OPT_BOOTSTRAP_CA_CERT,        OPT_NO_LOCAL_PORT,        OPT_NO_SLICING    };    static struct option long_options[] = {        {"interfaces",  required_argument, 0, 'i'},        {"local-port",  required_argument, 0, 'L'},        {"no-local-port", no_argument, 0, OPT_NO_LOCAL_PORT},        {"datapath-id", required_argument, 0, 'd'},        {"multiconn",     no_argument, 0, 'm'},        {"verbose",     optional_argument, 0, 'v'},        {"help",        no_argument, 0, 'h'},        {"version",     no_argument, 0, 'V'},        {"no-slicing",  no_argument, 0, OPT_NO_SLICING},        {"mfr-desc",    required_argument, 0, OPT_MFR_DESC},        {"hw-desc",     required_argument, 0, OPT_HW_DESC},        {"sw-desc",     required_argument, 0, OPT_SW_DESC},        {"dp_desc",  required_argument, 0, OPT_DP_DESC},        {"serial_num",  required_argument, 0, OPT_SERIAL_NUM},        DAEMON_LONG_OPTIONS,#ifdef HAVE_OPENSSL        VCONN_SSL_LONG_OPTIONS        {"bootstrap-ca-cert", required_argument, 0, OPT_BOOTSTRAP_CA_CERT},#endif        {0, 0, 0, 0},    };    char *short_options = long_options_to_short_options(long_options);    for (;;) {        int indexptr;        int c;        c = getopt_long(argc, argv, short_options, long_options, &indexptr);        if (c == -1) {            break;        }        switch (c) {        case 'd': {            uint64_t dpid;            if (strlen(optarg) != 12                || strspn(optarg, "0123456789abcdefABCDEF") != 12) {                ofp_fatal(0, "argument to -d or --datapath-id must be "                          "exactly 12 hex digits");            }            dpid = strtoll(optarg, NULL, 16);            if (!dpid) {                ofp_fatal(0, "argument to -d or --datapath-id must "                          "be nonzero");            }            dp_set_dpid(dp, dpid);            break;        }                case 'm': {            use_multiple_connections = true;            break;        }                case 'h':            usage();        case 'V':            printf("%s %s compiled "__DATE__" "__TIME__"/n",                   program_name, VERSION BUILDNR);            exit(EXIT_SUCCESS);        case 'v':            vlog_set_verbosity(optarg);            break;        case 'i':            if (!port_list) {                port_list = optarg;            } else {                port_list = xasprintf("%s,%s", port_list, optarg);            }            break;        case 'L':            local_port = optarg;            break;        case OPT_NO_LOCAL_PORT:            local_port = NULL;            break;        case OPT_MFR_DESC:            dp_set_mfr_desc(dp, optarg);            break;//.........这里部分代码省略.........
开发者ID:ofplus,项目名称:ofsoftswitch13,代码行数:101,


示例28: var_set

/* * Add given variable with given value to file, overwriting any * previous occurrence. */intvar_set(const char *fname, const char *variable, const char *value){	FILE   *fp;	FILE   *fout;	char   *tmpname;	int     fd;	char   *line;	size_t  len;	size_t  varlen;	Boolean done;	struct stat st;	varlen = strlen(variable);	if (varlen == 0)		return 0;	fp = fopen(fname, "r");	if (fp == NULL) {		if (errno != ENOENT) {			warn("var_set: can't open '%s' for reading", fname);			return -1;		}		if (value == NULL)			return 0; /* Nothing to do */	}	tmpname = xasprintf("%s.XXXXXX", fname);	if ((fd = mkstemp(tmpname)) < 0) {		free(tmpname);		if (fp != NULL)			fclose(fp);		warn("var_set: can't open temp file for '%s' for writing",		      fname);		return -1;	}	if (chmod(tmpname, 0644) < 0) {		close(fd);		if (fp != NULL)			fclose(fp);		free(tmpname);		warn("var_set: can't set permissions for temp file for '%s'",		      fname);		return -1;	}	if ((fout=fdopen(fd, "w")) == NULL) {		close(fd);		remove(tmpname);		free(tmpname);		if (fp != NULL)			fclose(fp);		warn("var_set: can't open temp file for '%s' for writing",		      fname);		return -1;	}	done = FALSE;	if (fp) {		while ((line = fgetln(fp, &len)) != (char *) NULL) {			if (var_cmp(line, len, variable, varlen) == NULL)				fprintf(fout, "%.*s", (int)len, line);			else {				if (!done && value) {					var_print(fout, variable, value);					done = TRUE;				}			}		}		(void) fclose(fp);	}	if (!done && value)		var_print(fout, variable, value);	if (fclose(fout) < 0) {		free(tmpname);		warn("var_set: write error for '%s'", fname);		return -1;	}	if (stat(tmpname, &st) < 0) {		free(tmpname);		warn("var_set: cannot stat tempfile for '%s'", fname);		return -1;	}	if (st.st_size == 0) {		if (remove(tmpname) < 0) {			free(tmpname);			warn("var_set: cannot remove tempfile for '%s'",			     fname);			return -1;		}		free(tmpname);		if (remove(fname) < 0) {//.........这里部分代码省略.........
开发者ID:gosudream,项目名称:netbsd-src,代码行数:101,


示例29: cairo_ref_name_for_test_target_format

static char *cairo_ref_name_for_test_target_format (const char *test_name,				       const char *target_name,				       const char *format){    char *ref_name = NULL;    /* First look for a previous build for comparison. */    if (refdir) {	xasprintf (&ref_name, "%s/%s-%s-%s%s", refdir,		   test_name,		   target_name,		   format,		   CAIRO_TEST_PNG_SUFFIX);	if (access (ref_name, F_OK) != 0)	    free (ref_name);	else	    goto done;    }    /* Next look for a target/format-specific reference image. */    xasprintf (&ref_name, "%s/%s-%s-%s%s", srcdir,	       test_name,	       target_name,	       format,	       CAIRO_TEST_REF_SUFFIX);    if (access (ref_name, F_OK) != 0)	free (ref_name);    else	goto done;    /* Next, look for taget-specifc reference image. */    xasprintf (&ref_name, "%s/%s-%s%s", srcdir,	       test_name,	       target_name,	       CAIRO_TEST_REF_SUFFIX);    if (access (ref_name, F_OK) != 0)	free (ref_name);    else	goto done;    /* Next, look for format-specifc reference image. */    xasprintf (&ref_name, "%s/%s-%s%s", srcdir,	       test_name,	       format,	       CAIRO_TEST_REF_SUFFIX);    if (access (ref_name, F_OK) != 0)	free (ref_name);    else	goto done;    /* Finally, look for the standard reference image. */    xasprintf (&ref_name, "%s/%s%s", srcdir,	       test_name,	       CAIRO_TEST_REF_SUFFIX);    if (access (ref_name, F_OK) != 0)	free (ref_name);    else	goto done;    ref_name = NULL;done:    return ref_name;}
开发者ID:Dirbaio,项目名称:libgdiplus,代码行数:65,



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


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