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

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

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

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

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

示例1: writefile

static voidwritefile(time_t runtimer, char queue){/* This does most of the work if at or batch are invoked for writing a job. */    long jobno;    char *ap, *ppos, *mailname;    struct passwd *pass_entry;    struct stat statbuf;    int fdes, lockdes, fd2;    FILE *fp, *fpin;    struct sigaction act;    char **atenv;    int ch;    mode_t cmask;    struct flock lock;    #ifdef __FreeBSD__    (void) setlocale(LC_TIME, "");#endif/* Install the signal handler for SIGINT; terminate after removing the * spool file if necessary */    act.sa_handler = sigc;    sigemptyset(&(act.sa_mask));    act.sa_flags = 0;    sigaction(SIGINT, &act, NULL);    ppos = atfile + strlen(ATJOB_DIR);    /* Loop over all possible file names for running something at this     * particular time, see if a file is there; the first empty slot at any     * particular time is used.  Lock the file LFILE first to make sure     * we're alone when doing this.     */    PRIV_START    if ((lockdes = open(LFILE, O_WRONLY | O_CREAT, S_IWUSR | S_IRUSR)) < 0)	perr("cannot open lockfile " LFILE);    lock.l_type = F_WRLCK; lock.l_whence = SEEK_SET; lock.l_start = 0;    lock.l_len = 0;    act.sa_handler = alarmc;    sigemptyset(&(act.sa_mask));    act.sa_flags = 0;    /* Set an alarm so a timeout occurs after ALARMC seconds, in case     * something is seriously broken.     */    sigaction(SIGALRM, &act, NULL);    alarm(ALARMC);    fcntl(lockdes, F_SETLKW, &lock);    alarm(0);    if ((jobno = nextjob()) == EOF)	perr("cannot generate job number");    sprintf(ppos, "%c%5lx%8lx", queue, 	    jobno, (unsigned long) (runtimer/60));    for(ap=ppos; *ap != '/0'; ap ++)	if (*ap == ' ')	    *ap = '0';    if (stat(atfile, &statbuf) != 0)	if (errno != ENOENT)	    perr("cannot access " ATJOB_DIR);    /* Create the file. The x bit is only going to be set after it has     * been completely written out, to make sure it is not executed in the     * meantime.  To make sure they do not get deleted, turn off their r     * bit.  Yes, this is a kluge.     */    cmask = umask(S_IRUSR | S_IWUSR | S_IXUSR);    if ((fdes = creat(atfile, O_WRONLY)) == -1)	perr("cannot create atjob file");     if ((fd2 = dup(fdes)) <0)	perr("error in dup() of job file");    if(fchown(fd2, real_uid, real_gid) != 0)	perr("cannot give away file");    PRIV_END    /* We no longer need suid root; now we just need to be able to write     * to the directory, if necessary.     */    REDUCE_PRIV(DAEMON_UID, DAEMON_GID)    /* We've successfully created the file; let's set the flag so it      * gets removed in case of an interrupt or error.     */    fcreated = 1;//.........这里部分代码省略.........
开发者ID:2asoft,项目名称:freebsd,代码行数:101,


示例2: command_inject

static int command_inject(args_t * args){	assert(args != NULL);	struct stat st;	if (stat(args->path, &st) != 0) {		ERRNO(errno);		return -1;	}	if (!S_ISREG(st.st_mode)) {		ERRNO(errno);		return -1;	}	FILE *i = fopen(args->path, "r");	if (i == NULL) {		ERRNO(errno);		return-1;	}	FILE *o = fopen(args->file, "w");	if (o == NULL) {		ERRNO(errno);		return -1;	}#define INPUT_SIZE		(4096 - (4096 / ECC_SIZE))	char input[INPUT_SIZE];	// 4KB less 512 ECC bytes#undef INPUT_SIZE	size_t count = 0;	while (count < st.st_size) {		clearerr(i);		size_t rc = fread(input, 1, sizeof input, i);		if (rc == 0) {			int err = ferror(i);			if (err) {				ERRNO(errno);				return -1;			} else				break;		}		count += rc;#define OUTPUT_SIZE		4096		char output[OUTPUT_SIZE];#undef OUTPUT_SIZE		memset(output + sizeof input, 0, sizeof output - sizeof input);		rc = (rc + 7) & ~7;	// 8-byte alignment		ssize_t injected_size = 0;		if (args->p8 == f_P8)			injected_size =			    p8_ecc_inject(output, sizeof output, input, rc);		else			injected_size =			    sfc_ecc_inject(output, sizeof output, input, rc);		if (injected_size < 0) {			ERRNO(errno);			return -1;		}		clearerr(o);		rc = fwrite(output, 1, injected_size, o);		if (rc == 0) {			int err = ferror(o);			if (err) {				ERRNO(errno);				return -1;			}		}	}	if (fclose(i) == EOF) {		ERRNO(errno);		return -1;	}	if (fclose(o) == EOF) {		ERRNO(errno);		return -1;	}	return 0;}
开发者ID:eddiejames,项目名称:ffs,代码行数:90,


示例3: command_hexdump

static int command_hexdump(args_t * args){	assert(args != NULL);	struct stat st;	if (stat(args->path, &st) != 0) {		ERRNO(errno);		return -1;	}	if (!S_ISREG(st.st_mode)) {		ERRNO(errno);		return -1;	}	FILE *i = fopen(args->path, "r");	if (i == NULL) {		ERRNO(errno);		return -1;	}	FILE *o = stdout;	if (args->file != NULL) {		o = fopen(args->file, "w");		if (o == NULL) {			ERRNO(errno);			return -1;		}	}#define INPUT_SIZE 		4086	char input[INPUT_SIZE];	// multiple of 9-bytes#undef INPUT_SIZE	if (setvbuf(i, NULL, _IOFBF, __round_pow2(sizeof input)) != 0) {		ERRNO(errno);		return -1;	}	size_t count = 0;	while (count < st.st_size) {		clearerr(i);		size_t rc = fread(input, 1, sizeof input, i);		if (rc == 0) {			int err = ferror(i);			if (err) {				ERRNO(errno);				return -1;			} else				break;		}		if (args->p8 == f_P8)			p8_ecc_dump(o, count, input, rc);		else			sfc_ecc_dump(o, count, input, rc);		count += rc;	}	if (fclose(i) == EOF) {		ERRNO(errno);		return -1;	}	if (o != stdout) {		if (fclose(o) == EOF) {			ERRNO(errno);			return -1;		}	}	return 0;}
开发者ID:eddiejames,项目名称:ffs,代码行数:74,


示例4: gpsd_start

static intgpsd_start(	int     unit,	peerT * peer){	clockprocT * const pp = peer->procptr;	gpsd_unitT * const up = emalloc_zero(sizeof(*up));	struct stat sb;	/* initialize the unit structure */	up->fdt      = -1;	up->addr     = s_gpsd_addr;	up->tickpres = TICKOVER_LOW;	/* setup refclock processing */	up->unit    = unit;	pp->unitptr = (caddr_t)up;	pp->io.fd   = -1;	pp->io.clock_recv = gpsd_receive;	pp->io.srcclock   = peer;	pp->io.datalen    = 0;	pp->a_lastcode[0] = '/0';	pp->lencode       = 0;	pp->clockdesc     = DESCRIPTION;	memcpy(&pp->refid, REFID, 4);	/* Initialize miscellaneous variables */	peer->precision = PRECISION;	/* Create the device name and check for a Character Device. It's	 * assumed that GPSD was started with the same link, so the	 * names match. (If this is not practicable, we will have to	 * read the symlink, if any, so we can get the true device	 * file.)	 */	if (-1 == myasprintf(&up->device, "%s%u", s_dev_stem, unit)) {	    msyslog(LOG_ERR, "%s clock device name too long",		    refnumtoa(&peer->srcadr));	    goto dev_fail;	}	if (-1 == stat(up->device, &sb) || !S_ISCHR(sb.st_mode)) {		msyslog(LOG_ERR, "%s: '%s' is not a character device",			refnumtoa(&peer->srcadr), up->device);	    goto dev_fail;	}	LOGIF(CLOCKINFO,	      (LOG_NOTICE, "%s: startup, device is '%s'",	       refnumtoa(&peer->srcadr), up->device));	return TRUE;dev_fail:	/* On failure, remove all UNIT ressources and declare defeat. */	INSIST (up);	free(up->device);	free(up);	pp->unitptr = (caddr_t)NULL;	return FALSE;}
开发者ID:execunix,项目名称:vinos,代码行数:61,


示例5: main

    intmain(int argc, char *argv[]){    int		found = 0;    FILE	*fd;#ifdef WIN3264    int		i;    struct stat st;    char	icon[BUFSIZE];    char	path[BUFSIZE];    char	popup_path[BUFSIZE];    /* The nsis uninstaller calls us with a "-nsis" argument. */    if (argc == 2 && stricmp(argv[1], "-nsis") == 0)	interactive = FALSE;    else#endif	interactive = TRUE;    /* Initialize this program. */    do_inits(argv);    printf("This program will remove the following items:/n");#ifdef WIN3264    if (popup_gvim_path(popup_path))    {	printf(" - the /"Edit with Vim/" entry in the popup menu/n");	printf("   which uses /"%s/"/n", popup_path);	if (interactive)	    printf("/nRemove it (y/n)? ");	if (!interactive || confirm())	{	    remove_popup();	    /* Assume the "Open With" entry can be removed as well, don't	     * bother the user with asking him again. */	    remove_openwith();	}    }    else if (openwith_gvim_path(popup_path))    {	printf(" - the Vim /"Open With.../" entry in the popup menu/n");	printf("   which uses /"%s/"/n", popup_path);	printf("/nRemove it (y/n)? ");	if (confirm())	    remove_openwith();    }    if (get_shell_folder_path(path, "desktop"))    {	printf("/n");	for (i = 0; i < ICON_COUNT; ++i)	{	    sprintf(icon, "%s//%s", path, icon_link_names[i]);	    if (stat(icon, &st) == 0)	    {		printf(" - the /"%s/" icon on the desktop/n", icon_names[i]);		++found;	    }	}	if (found > 0)	{	    if (interactive)		printf("/nRemove %s (y/n)? ", found > 1 ? "them" : "it");	    if (!interactive || confirm())		remove_icons();	}    }    if (get_shell_folder_path(path, VIM_STARTMENU)	    && stat(path, &st) == 0)    {	printf("/n - the /"%s/" entry in the Start Menu/n", VIM_STARTMENU);	if (interactive)	    printf("/nRemove it (y/n)? ");	if (!interactive || confirm())	    remove_start_menu();    }#endif    printf("/n");    found = remove_batfiles(0);    if (found > 0)    {	if (interactive)	    printf("/nRemove %s (y/n)? ", found > 1 ? "them" : "it");	if (!interactive || confirm())	    remove_batfiles(1);    }    fd = fopen("gvim.exe", "r");    if (fd != NULL)    {	fclose(fd);	printf("gvim.exe detected.  Attempting to unregister gvim with OLE/n");	system("gvim.exe -silent -unregister");    }    delete_uninstall_key();//.........这里部分代码省略.........
开发者ID:11liju,项目名称:macvim,代码行数:101,


示例6: get_file_size

int get_file_size(char *name) {	struct stat filestatus;	stat(name, &filestatus );	return filestatus.st_size;}
开发者ID:quanghn,项目名称:visquajpegcompress,代码行数:5,


示例7: read_persistent_state

static gboolean read_persistent_state(GAPersistentState *pstate,                                      const gchar *path, gboolean frozen){    GKeyFile *keyfile = NULL;    GError *gerr = NULL;    struct stat st;    gboolean ret = true;    g_assert(pstate);    if (stat(path, &st) == -1) {        /* it's okay if state file doesn't exist, but any other error         * indicates a permissions issue or some other misconfiguration         * that we likely won't be able to recover from.         */        if (errno != ENOENT) {            g_critical("unable to access state file at path %s: %s",                       path, strerror(errno));            ret = false;            goto out;        }        /* file doesn't exist. initialize state to default values and         * attempt to save now. (we could wait till later when we have         * modified state we need to commit, but if there's a problem,         * such as a missing parent directory, we want to catch it now)         *         * there is a potential scenario where someone either managed to         * update the agent from a version that didn't use a key store         * while qemu-ga thought the filesystem was frozen, or         * deleted the key store prior to issuing a fsfreeze, prior         * to restarting the agent. in this case we go ahead and defer         * initial creation till we actually have modified state to         * write, otherwise fail to recover from freeze.         */        set_persistent_state_defaults(pstate);        if (!frozen) {            ret = write_persistent_state(pstate, path);            if (!ret) {                g_critical("unable to create state file at path %s", path);                ret = false;                goto out;            }        }        ret = true;        goto out;    }    keyfile = g_key_file_new();    g_key_file_load_from_file(keyfile, path, 0, &gerr);    if (gerr) {        g_critical("error loading persistent state from path: %s, %s",                   path, gerr->message);        ret = false;        goto out;    }    persistent_state_from_keyfile(pstate, keyfile);out:    if (keyfile) {        g_key_file_free(keyfile);    }    if (gerr) {        g_error_free(gerr);    }    return ret;}
开发者ID:Marshalzxy,项目名称:qemu,代码行数:69,


示例8: tod_set

int tod_set(const struct timeval *tv, const int *tzsec_off){	struct stat sb;	struct timeval tval;        struct tm tm;	rule_struct dst_rules[2];	char buf[64+TZ_BUFLEN] = {'T','Z','i','f','2', 0};	char *tzstr = &buf[54];	int tzoff, dstoff;	int fd;	tzset();	if ((tzsec_off != NULL) && (*tzsec_off != -timezone)) {		// We must set the timezone offset but preserve any existing DST rule				// Read existing DST Rule ?		// is /etc/localtime present?		if (stat("/etc/localtime", &sb) == 0) {			if (get_dst_rules(dst_rules) == -1)				return -1;			// modify rule info and rewrite			tzoff = -(*tzsec_off);			dstoff = tzoff - (dst_rules[0].gmt_offset - dst_rules[1].gmt_offset);			// Fill std offset			tzstr += sprintf(tzstr, "/nATCST%2.2d:%2.2d:%2.2d",				tzoff/3600, (tzoff%3600)/60, (tzoff%3600)%60);			// Fill dst rules, if any			if (!!dst_rules[1].tzname[0]) {				// Fill dst offset				tzstr += sprintf(tzstr, "ATCDT%2.2d:%2.2d:%2.2d",					dstoff/3600, (dstoff%3600)/60, (dstoff%3600)%60);				// Fill begin dst rule				tzstr += sprintf(tzstr, ",M%d.%d.%d/%2.2ld:%2.2ld:%2.2ld",					dst_rules[0].month,					dst_rules[0].week,					dst_rules[0].day,					dst_rules[0].dst_offset/3600,					(dst_rules[0].dst_offset%3600)/60,					(dst_rules[0].dst_offset%3600)%60);				// Fill end dst rule				tzstr += sprintf(tzstr, ",M%d.%d.%d/%2.2ld:%2.2ld:%2.2ld",					dst_rules[1].month,					dst_rules[1].week,					dst_rules[1].day,					dst_rules[1].dst_offset/3600,					(dst_rules[1].dst_offset%3600)/60,					(dst_rules[1].dst_offset%3600)%60);			}			*tzstr++ = '/n';			// Write to temp file			fd = open("/etc/localtime~", O_RDWR|O_CREAT|O_TRUNC);			if (fd >= 0) {				write(fd, buf, (tzstr-buf));				fsync(fd);				close(fd);			} else {				return -1;			}			// Rename to actual filename (or move to /usr/share/zoneinfo and link?)			if (rename("/etc/localtime~", "/etc/localtime") == -1)				return -1;					}		// Update globals with new timezone		tzset();	}		if (tv != NULL) {		tval = *tv;                if (tzsec_off == NULL)                        tzset();                gmtime_r(&tval.tv_sec, &tm);                tm.tm_isdst = -1;                if (mktime(&tm) == -1)                        return -1;		tval.tv_sec += timezone - ((daylight && tm.tm_isdst)?3600:0);		settimeofday(&tval, NULL);	}	return 0;}
开发者ID:peterSVS,项目名称:APIRI,代码行数:79,


示例9: list_modules

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


示例10: open_dso

static int open_dso(const char * path, pid_t * pidp, rpm_loff_t *fsizep){    static const char * cmd = NULL;    static int initted = 0;    int fdno;    if (!initted) {	cmd = rpmExpand("%{?__prelink_undo_cmd}", NULL);	initted++;    }    if (pidp) *pidp = 0;    if (fsizep) {	struct stat sb, * st = &sb;	if (stat(path, st) < 0)	    return -1;	*fsizep = st->st_size;    }    fdno = open(path, O_RDONLY);    if (fdno < 0)	return fdno;    if (!(cmd && *cmd))	return fdno;    if (pidp != NULL && is_prelinked(fdno)) {	int pipes[2];	pid_t pid;	close(fdno);	pipes[0] = pipes[1] = -1;	if (pipe(pipes) < 0)	    return -1;	pid = fork();	if (pid < 0) {	    close(pipes[0]);	    close(pipes[1]);	    return -1;	}	if (pid == 0) {	    ARGV_t av, lib;	    int dfd;	    argvSplit(&av, cmd, " ");	    close(pipes[0]);	    dfd = dup2(pipes[1], STDOUT_FILENO);	    close(pipes[1]);	    if (dfd >= 0 && (lib = argvSearch(av, "library", NULL)) != NULL) {		*lib = (char *) path;		unsetenv("MALLOC_CHECK_");		execve(av[0], av+1, environ);	    }	    _exit(127); /* not normally reached */	} else {	    *pidp = pid;	    fdno = pipes[0];	    close(pipes[1]);	}    }    return fdno;}
开发者ID:PerilousApricot,项目名称:rpm,代码行数:66,


示例11: CASE

// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.// See the License for the specific language governing permissions and// limitations under the License.#include <common.cxx>#include <tar>#include <sys/mman.h>#include <sys/stat.h>#include <fcntl.h>#include <unistd.h>CASE("Reading single entry tar file"){  tar::Reader r;  struct stat st;  int res = stat("test-single.tar", &st);  EXPECT(res != -1);  size_t size = st.st_size;  int fd = open("test-single.tar", O_RDONLY);  EXPECT_NOT(fd == -1);  const uint8_t *mem = (const uint8_t *)mmap(0, size, PROT_READ, MAP_PRIVATE, fd, 0);  tar::Tar tar = r.read_uncompressed(mem, size);  EXPECT(tar.num_elements() == 1);  auto names = tar.element_names();  EXPECT(names.size() == 1);  const auto& elements = tar.elements();  EXPECT(elements.size() == 1);  const auto& e = elements.at(0);  EXPECT_NOT(e.is_dir());  EXPECT(e.typeflag_is_set());  EXPECT(e.typeflag() == REGTYPE); // regular file
开发者ID:AnnikaH,项目名称:IncludeOS,代码行数:31,


示例12: main

//.........这里部分代码省略.........        xmlFreeParserCtxt(ctxt);        if (!doc) {            fprintf(stderr, "Failed to parse XML document/n");            break;        }        node = xmlDocGetRootElement(doc);        if (!node || xmlStrcmp(node->name, BAD_CAST "supplementalData")) {            fprintf(stderr, "Incorrect root node/n");            goto done;        }        for (node = xmlFirstElementChild(node);             node && xmlStrcmp(node->name, BAD_CAST "windowsZones");             node = xmlNextElementSibling(node));        if (!node) {            fprintf(stderr, "Missing windowsZones node/n");            goto done;        }        node = xmlFirstElementChild(node);        if (!node || xmlStrcmp(node->name, BAD_CAST "mapTimezones")) {            fprintf(stderr, "Missing mapTimezones node/n");            goto done;        }        if (chdir(prefix)) {            fprintf(stderr, "chdir(%s) failed/n", prefix);            goto done;        }        for (node = xmlFirstElementChild(node);             node;             node = xmlNextElementSibling(node)) {            if (!xmlStrcmp(node->name, BAD_CAST "mapZone") &&                !xmlStrcmp(xmlGetProp(node, BAD_CAST "territory"),                           BAD_CAST "001")) {                const char *tzid, *alias;                buf_setcstr(&tzidbuf,                            (const char *) xmlGetProp(node, BAD_CAST "type"));                buf_appendcstr(&tzidbuf, ".ics");                tzid = buf_cstring(&tzidbuf);                buf_setcstr(&aliasbuf,                            (const char *) xmlGetProp(node, BAD_CAST "other"));                buf_appendcstr(&aliasbuf, ".ics");                alias = buf_cstring(&aliasbuf);                if (verbose) printf("/tLINK: %s -> %s/n", alias, tzid);                if (symlink(tzid, alias)) {                    if (errno == EEXIST) {                        struct stat sbuf;                        if (stat(alias, &sbuf)) {                            fprintf(stderr, "stat(%s) failed: %s/n",                                    alias, strerror(errno));                            errno = EEXIST;                        }                        else if (sbuf.st_mode & S_IFLNK) {                            char link[MAX_MAILBOX_PATH+1];                            int n = readlink(alias, link, MAX_MAILBOX_PATH);                            if (n == -1) {                                fprintf(stderr, "readlink(%s) failed: %s/n",                                        alias, strerror(errno));                                errno = EEXIST;                            }                            else if (n == (int) strlen(tzid) &&                                     !strncmp(tzid, link, n)) {                                errno = 0;                            }                        }                    }                    if (errno) {                        fprintf(stderr, "symlink(%s, %s) failed: %s/n",                                tzid, alias, strerror(errno));                    }                }            }        }  done:        buf_free(&aliasbuf);        buf_free(&tzidbuf);        xmlFreeDoc(doc);        break;    }    case NONE:        r = 2;        usage();        break;    }    cyrus_done();    return r;}
开发者ID:Distrotech,项目名称:cyrus-imapd,代码行数:101,


示例13: running_check

voidrunning_check(int check_type){    int        total_num=0, i, j, k;    FILE      *fp;    char       line[2][LEN_40960];    char       filename[LEN_128] = {0};    char       tmp[10][LEN_4096];    char       check[LEN_40960] = {0};    char       host_name[LEN_64] = {0};    struct     module *mod = NULL;    struct     stat statbuf;    time_t     nowtime;    double    *st_array;    /* get hostname */    if (0 != gethostname(host_name, sizeof(host_name))) {        do_debug(LOG_FATAL, "tsar -check: gethostname err, errno=%d", errno);    }    i = 0;    while (host_name[i]) {        if (!isprint(host_name[i++])) {            host_name[i-1] = '/0';            break;        }    }    memset(tmp, 0, 10 * LEN_4096);    sprintf(check, "%s/ttsar/t", host_name);    sprintf(filename, "%s", conf.output_file_path);    fp = fopen(filename, "r");    if (!fp) {        do_debug(LOG_FATAL, "unable to open the log file %s./n", filename);    }    /* check file update time */    stat(filename, &statbuf);    time(&nowtime);    if (nowtime - statbuf.st_mtime > 300) {        do_debug(LOG_FATAL, "/var/log/tsar.data is far away from now, now time is %d, last time is %d", nowtime, statbuf.st_mtime);    }    /* get file len */    memset(&line[0], 0, LEN_40960);    total_num =0;    /* find two /n from end*/    if (fseek(fp, -1, SEEK_END) != 0) {        do_debug(LOG_FATAL, "fseek error:%s", strerror(errno));    }    while (1) {        if (fgetc(fp) == '/n') {            ++total_num;        }        if (total_num == 3) {            break;        }        if (fseek(fp, -2, SEEK_CUR) != 0) {            /* just 1 or 2 line, goto file header */            if (fseek(fp, 0, SEEK_SET) != 0) {                do_debug(LOG_FATAL, "fseek error:%s", strerror(errno));            }            break;        }    }    /*FIX ME*/    if (total_num == 0) {        if (fclose(fp) < 0) {            do_debug(LOG_FATAL, "fclose error:%s", strerror(errno));        }        memset(filename, 0, sizeof(filename));        sprintf(filename, "%s.1", conf.output_file_path);        fp = fopen(filename, "r");        if (!fp) {            do_debug(LOG_FATAL, "unable to open the log file %s./n", filename);        }        total_num = 0;        memset(&line[0], 0, 2 * LEN_40960);        /* count tsar.data.1 lines */        if (fseek(fp, -1, SEEK_END) != 0) {            do_debug(LOG_FATAL, "fseek error:%s", strerror(errno));        }        while (1) {            if (fgetc(fp) == '/n') {                ++total_num;            }            if (total_num == 3) {                break;            }            if (fseek(fp, -2, SEEK_CUR) != 0) {                if (fseek(fp, 0, SEEK_SET) != 0) {                    do_debug(LOG_FATAL, "fseek error:%s", strerror(errno));                }                break;            }        }        if (total_num < 2) {            do_debug(LOG_FATAL, "not enough lines at log file %s./n", filename);        }        memset(&line[0], 0, LEN_40960);        if (!fgets(line[0], LEN_40960, fp)) {            do_debug(LOG_FATAL, "fgets error:%s", strerror(errno));        }//.........这里部分代码省略.........
开发者ID:AstroProfundis,项目名称:tsar,代码行数:101,


示例14: return

 bool Util::fileExists(std::string filename) {     struct stat file_info;     return (stat(filename.c_str(), &file_info) == 0); }
开发者ID:hach-que,项目名称:AppTools,代码行数:5,


示例15: write_udhcpd_conf

/**   * Write udhcpd.conf  * @ipforward : NULL if we want a simple config, otherwise include dns info etc...  */static int write_udhcpd_conf(struct ipforward_data *ipforward, struct mode_list_elem *data){  FILE *conffile;  char *ip, *interface;  char *ipstart, *ipend;  int dot = 0, i = 0, test;  struct stat st;  /* /tmp is often tmpfs, so we avoid writing to flash */  conffile = fopen("/tmp/udhcpd.conf", "w");  if(conffile == NULL)  {	log_debug("Error creating /etc/udhcpd.conf!/n");	return(1);  }  /* generate start and end ip based on the setting */  ip = get_network_ip();  if(ip == NULL)  {	ip = strdup("192.168.2.15");  }  ipstart = malloc(sizeof(char)*15);  ipend = malloc(sizeof(char)*15);  while(i < 15)  {        if(dot < 3)        {                if(ip[i] == '.')                        dot ++;                ipstart[i] = ip[i];                ipend[i] = ip[i];        }        else        {                ipstart[i] = '/0';                ipend[i] = '/0';                break;        }        i++;  }  strcat(ipstart,"1");  strcat(ipend, "10");  interface = get_interface(data);  /* print all data in the file */  fprintf(conffile, "start/t%s/n", ipstart);  fprintf(conffile, "end/t%s/n", ipend);  fprintf(conffile, "interface/t%s/n", interface);  fprintf(conffile, "option/tsubnet/t255.255.255.0/n");  if(ipforward != NULL)  {	if(!ipforward->dns1 || !ipforward->dns2)	{		log_debug("No dns info!");	}	else		fprintf(conffile, "opt/tdns/t%s %s/n", ipforward->dns1, ipforward->dns2);	fprintf(conffile, "opt/trouter/t%s/n", ip);  }  free(ipstart);  free(ipend);  free(ip);  free(interface);  fclose(conffile);  log_debug("/etc/udhcpd.conf written./n");  /* check if it is a symlink, if not remove and link, create the link if missing */  test = stat("/etc/udhcpd.conf", &st);  /* if stat fails there is no file or link */  if(test == -1)	goto link;  /* if it is not a link we remove it, else we expect the right link to be there */  if((st.st_mode & S_IFMT) != S_IFLNK)  {	unlink("/etc/udhcpd.conf");  }  else	goto end;link:  symlink("/tmp/udhcpd.conf", "/etc/udhcpd.conf");end:  return(0);}
开发者ID:iamer,项目名称:usb-moded,代码行数:92,


示例16: main

int main(int argc, char **argv){	if (argc != 4)	{		fprintf (stdout, "usage: %s reserved_words_file source_file output_dir/n", argv[0]);		exit(1);	}	fprintf(stdout, "-- Lexer begin --/n");	FILE *f;	ParserData *parser_data = (ParserData *)malloc(sizeof(ParserData));	/* tokenize reserved words file */	char line[200];	ReservedWord *head, *curr;	head = NULL;	f = fopen (argv[1], "r");	if (f == NULL)	{		fprintf (stderr, "Can't open reserved words file!/n");		exit(1);	}	fprintf(stdout, "Parsing reserved words file.. ");	while (fgets (line, 200, f) != NULL)	{		curr = tokenize_reserved_word_str (line);		curr->next = head;		head = curr;	}	parser_data->reserved_words = head;	fclose(f);	fprintf(stdout,"ok/n");	/* tokenize input source file */	parser_data->source = fopen (argv[2], "r");	if (parser_data->source == NULL)	{		fprintf (stderr, "Can't open source file!/n");		exit(1);	}	char *output_dir = malloc(strlen(argv[3]));	strcpy (output_dir, argv[3]);	// ensure the output directory is present  	struct stat fileStat;	if (stat(output_dir, &fileStat) < 0)	{		mode_t process_mask = umask(0);		mkdir(output_dir, S_IRWXU | S_IRWXG | S_IRWXO);		umask(process_mask);		if (stat(output_dir, &fileStat) < 0)		{			fprintf (stderr, "Output directory does not exist!/n");			exit(1);		}	}	// strip trailing "/" from output dir	if (strcmp (&output_dir[strlen(output_dir)-1], "//") == 0)		output_dir[strlen(output_dir)-1] = 0;	// open listing file for writing	char *listing_filename = malloc(strlen(output_dir) + 9);	sprintf(listing_filename, "%s/listing", output_dir);	parser_data->listing = fopen (listing_filename, "w");	if (parser_data->listing == NULL)	{		fprintf (stderr, "Can't create listing file at %s!/n", listing_filename);		exit(1);	}	// open tokens file for writing	char *tokens_filename = malloc(strlen(output_dir) + 9);	sprintf(tokens_filename, "%s/tokens", output_dir);	parser_data->tokens = fopen (tokens_filename, "w");	if (parser_data->tokens == NULL)	{		fprintf (stderr, "Can't create tokens file at %s!/n", tokens_filename);		exit(1);	}	// token file header	fprintf (parser_data->tokens, "%-10s%-20s%-20s%s/n", "Line No.", "Lexeme", "TOKEN-TYPE", "ATTRIBUTE");	// initalize symbol table//.........这里部分代码省略.........
开发者ID:jaredtking,项目名称:cs4013-2,代码行数:101,


示例17: tagpopen

int tagpopen() {    dev_t devt;	struct stat     st;    int    rc = 0;    devt = makedev(TAGP_MAJOR, 0);    if (rc) {        if (errno == ENOENT) {            /* dev node does not exist. */            rc = mkdir(DEVICE_NAME, (S_IFDIR | S_IRWXU |                                                S_IRGRP | S_IXGRP |                                                S_IROTH | S_IXOTH));        } else {            printf("ERROR: Problem with Base dev directory.  Error code from stat() is %d/n/n", errno);        }    } else {        if (!(st.st_mode & S_IFDIR)) {            rc = unlink(DEVICE_NAME);            if (!rc) {                rc = mkdir(DEVICE_NAME, (S_IFDIR | S_IRWXU |                                                S_IRGRP | S_IXGRP |                                                S_IROTH | S_IXOTH));            }        }    }    /*     * Check for the /dev/tbase node, and create if it does not     * exist.     */    rc = stat(DEVICE_NAME, &st);    if (rc) {        if (errno == ENOENT) {            /* dev node does not exist */            rc = mknod(DEVICE_NAME, (S_IFCHR | S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP), devt);        } else {            printf("ERROR:Problem with tbase device node directory.  Error code form stat() is %d/n/n", errno);        }    } else {        /*         * /dev/tbase CHR device exists.  Check to make sure it is for a         * block device and that it has the right major and minor.         */        if ((!(st.st_mode & S_IFCHR)) ||             (st.st_rdev != devt)) {            /* Recreate the dev node. */            rc = unlink(DEVICE_NAME);            if (!rc) {                rc = mknod(DEVICE_NAME, (S_IFCHR | S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP), devt);            }        }    }    tagp_fd = open(DEVICE_NAME, O_RDWR);    if (tagp_fd < 0) {        printf("ERROR: Open of device %s failed %d errno = %d/n", DEVICE_NAME,tagp_fd, errno);        return errno;    }    else {        printf("Device opened successfully /n");      return 0;    }}
开发者ID:joyforu,项目名称:android-ltp-ndk,代码行数:70,


示例18: is_exist

bool is_exist(string filename) {	struct stat buf;	int result = stat(filename.c_str(), &buf);	return (result==0);}
开发者ID:quanghn,项目名称:visquajpegcompress,代码行数:5,


示例19: main

intmain(int argc, char **argv){    char *path;    struct stat st;    char *buffer;    FILE *fp;    int i, k;    int rewrites_count = sizeof (rewrites) / sizeof (struct rewrite);    if (argc != 2) {        printf("usage: %s <libvirtmod.pyd>", argv[0]);        return 1;    }    path = argv[1];    if (stat(path, &st) < 0) {        printf("error: could not stat '%s'/n", path);        return 1;    }    buffer = malloc(st.st_size + 1024);    fp = fopen(path, "rb");    if (fp == NULL) {        printf("error: could not open '%s' for reading/n", path);        return 1;    }    if (fread(buffer, 1, st.st_size, fp) != st.st_size) {        fclose(fp);        free(buffer);        printf("error: could not read from '%s'/n", path);        return 1;    }    fclose(fp);    for (i = 0; i < st.st_size - 100; ++i) {        for (k = 0; k < rewrites_count; ++k) {            if (memcmp(buffer + i, rewrites[k].from, rewrites[k].length) == 0) {                printf("rewriting '%s' at 0x%08x/n", rewrites[k].from, i);                memcpy(buffer + i, rewrites[k].to, rewrites[k].length);                i += rewrites[k].length;            }        }    }    fp = fopen(path, "wb");    if (fp == NULL) {        free(buffer);        printf("error: could not open '%s' for writing/n", path);        return 1;    }    if (fwrite(buffer, 1, st.st_size, fp) != st.st_size) {        fclose(fp);        free(buffer);        printf("error: could not write to '%s'/n", path);        return 1;    }    fclose(fp);    free(buffer);    return 0;}
开发者ID:changliwei,项目名称:msys_setup,代码行数:70,


示例20: main

int main(int argc, char **argv){	idevice_t phone = NULL;	lockdownd_client_t client = NULL;	instproxy_client_t ipc = NULL;	instproxy_error_t err;	np_client_t np = NULL;	afc_client_t afc = NULL;#ifdef HAVE_LIBIMOBILEDEVICE_1_1_5	lockdownd_service_descriptor_t service = NULL;#else	uint16_t service = 0;#endif	int res = 0;	char *bundleidentifier = NULL;	parse_opts(argc, argv);	argc -= optind;	argv += optind;	if (IDEVICE_E_SUCCESS != idevice_new(&phone, udid)) {		fprintf(stderr, "No iOS device found, is it plugged in?/n");		return -1;	}	if (LOCKDOWN_E_SUCCESS != lockdownd_client_new_with_handshake(phone, &client, "ideviceinstaller")) {		fprintf(stderr, "Could not connect to lockdownd. Exiting./n");		goto leave_cleanup;	}	if ((lockdownd_start_service		 (client, "com.apple.mobile.notification_proxy",		  &service) != LOCKDOWN_E_SUCCESS) || !service) {		fprintf(stderr,				"Could not start com.apple.mobile.notification_proxy!/n");		goto leave_cleanup;	}	np_error_t nperr = np_client_new(phone, service, &np);#ifdef HAVE_LIBIMOBILEDEVICE_1_1_5	if (service) {		lockdownd_service_descriptor_free(service);	}	service = NULL;#else	service = 0;#endif	if (nperr != NP_E_SUCCESS) {		fprintf(stderr, "Could not connect to notification_proxy!/n");		goto leave_cleanup;	}#ifdef HAVE_LIBIMOBILEDEVICE_1_1	np_set_notify_callback(np, notifier, NULL);#else	np_set_notify_callback(np, notifier);#endif	const char *noties[3] = { NP_APP_INSTALLED, NP_APP_UNINSTALLED, NULL };	np_observe_notifications(np, noties);run_again:#ifdef HAVE_LIBIMOBILEDEVICE_1_1_5	if (service) {		lockdownd_service_descriptor_free(service);	}	service = NULL;#else	service = 0;#endif	if ((lockdownd_start_service(client, "com.apple.mobile.installation_proxy",		  &service) != LOCKDOWN_E_SUCCESS) || !service) {		fprintf(stderr,				"Could not start com.apple.mobile.installation_proxy!/n");		goto leave_cleanup;	}	err = instproxy_client_new(phone, service, &ipc);#ifdef HAVE_LIBIMOBILEDEVICE_1_1_5	if (service) {		lockdownd_service_descriptor_free(service);	}	service = NULL;#else	service = 0;#endif	if (err != INSTPROXY_E_SUCCESS) {		fprintf(stderr, "Could not connect to installation_proxy!/n");		goto leave_cleanup;	}	setbuf(stdout, NULL);	if (last_status) {		free(last_status);		last_status = NULL;	}	notification_expected = 0;//.........这里部分代码省略.........
开发者ID:NitzanDavari,项目名称:ideviceinstaller,代码行数:101,


示例21: main

/*********************************************************************** * Main ***********************************************************************/int main(int ac, char **av){	int lc;			/* loop counter */	char *msg;		/* message returned from parse_opts */	char *fname;	char *desc;	int ind;	struct stat *stbuf;	struct sigaction sa, osa;    /***************************************************************     * parse standard options     ***************************************************************/	if ((msg = parse_opts(ac, av, (option_t *) NULL, NULL)) != (char *)NULL) {		tst_brkm(TBROK, NULL, "OPTION PARSING ERROR - %s", msg);		tst_exit();	}    /***************************************************************     * perform global setup for test     ***************************************************************/	setup();	/* set the expected errnos... */	TEST_EXP_ENOS(exp_enos);    /***************************************************************     * check looping state if -c option given     ***************************************************************/	for (lc = 0; TEST_LOOPING(lc); lc++) {		/* reset Tst_count in case we are looping. */		Tst_count = 0;		for (ind = 0; Test_cases[ind].desc != NULL; ind++) {			fname = Test_cases[ind].pathname;			desc = Test_cases[ind].desc;			stbuf = Test_cases[ind].stbuf;			if (stbuf == (struct stat *)-1) {				/* special sig11 case */				sa.sa_handler = &sig11_handler;				sigemptyset(&sa.sa_mask);				sa.sa_flags = 0;				sigaction(SIGSEGV, NULL, &osa);				sigaction(SIGSEGV, &sa, NULL);				if (setjmp(sig11_recover)) {					TEST_RETURN = -1;					TEST_ERRNO = EFAULT;				} else {					TEST(stat(fname, stbuf));				}				sigaction(SIGSEGV, &osa, NULL);			} else {				/*				 *  Call stat(2)				 */				TEST(stat(fname, stbuf));			}			/* check return code */			if (TEST_RETURN == -1) {				if (STD_FUNCTIONAL_TEST) {					if (TEST_ERRNO ==					    Test_cases[ind].exp_errno)						tst_resm(TPASS,							 "stat(<%s>, &stbuf) Failed, errno=%d",							 desc, TEST_ERRNO);					else						tst_resm(TFAIL,							 "stat(<%s>, &stbuf) Failed, errno=%d, expected errno:%d",							 desc, TEST_ERRNO,							 Test_cases[ind].							 exp_errno);				} else					Tst_count++;			} else {				tst_resm(TFAIL,					 "stat(<%s>, &stbuf) returned %ld, expected -1, errno:%d",					 desc, TEST_RETURN,					 Test_cases[ind].exp_errno);			}		}	}			/* End for TEST_LOOPING */    /***************************************************************     * cleanup and exit     ***************************************************************/	cleanup();	return 0;}				/* End main */
开发者ID:Federico2014,项目名称:edg4x-rose,代码行数:100,


示例22: myls

int myls(int argc, char *argv[]){		DIR *directory; //Stores a pointer to the directory	struct dirent *file;	int i;	struct stat sb;	struct passwd *pwd;	struct group *grp;	if(!strcmp(argv[1], "-l"))	{		for(i=2; i<argc; i++)		{			if(!access(argv[i],F_OK)) //Check if the directory specified by argv[i] exists.			{				directory=opendir(argv[i]); //If it exists, then open the directory.				if(directory!=NULL)				{					while((file=readdir(directory))!=NULL) //Read each entry in the directory.					{							if (stat(file->d_name, &sb) == -1) 						{							perror("stat");						}						//Display the type of file.						switch (sb.st_mode & S_IFMT) 						{							case S_IFBLK:  printf("b");            								       break;							case S_IFCHR:  printf("c");        								       break;							case S_IFDIR:  printf("d");               								       break;							case S_IFIFO:  printf("p");               								       break;							case S_IFLNK:  printf("l");                 								       break;							case S_IFREG:  printf("-");            								       break;							case S_IFSOCK: printf("s");                  								       break;							default:       printf("u");                								       break;						}						//Display the permissions for user, group and others.						(sb.st_mode & S_IRUSR)? printf("r"):printf("-");						(sb.st_mode & S_IWUSR)? printf("w"):printf("-");						(sb.st_mode & S_IXUSR)? printf("x"):printf("-");						(sb.st_mode & S_IRGRP)? printf("r"):printf("-");						(sb.st_mode & S_IWGRP)? printf("w"):printf("-");						(sb.st_mode & S_IXGRP)? printf("x"):printf("-");						(sb.st_mode & S_IROTH)? printf("r"):printf("-");						(sb.st_mode & S_IWOTH)? printf("w"):printf("-");						(sb.st_mode & S_IXOTH)? printf("x"):printf("-");							printf("%3ld ", (long) sb.st_nlink);//Display the number of links.						grp = getgrgid(sb.st_gid);						pwd = getpwuid(sb.st_uid);						printf("%11s %11s ", pwd->pw_name,grp->gr_name);//Display the username and group name.						printf("%4lld ",(long long) sb.st_size);//Display the size of the file.						printf("%s ",file->d_name);//Display the file name.						printf("%s",ctime(&sb.st_atime)); //Display the last access time of the file.					}				}			}		}		}	else if(!strcmp(argv[1], "-li"))	{		for(i=2; i<argc; i++)		{			if(!access(argv[i],F_OK)) //Check if the directory specified by argv[i] exists.			{				directory=opendir(argv[i]); //If it exists, then open the directory.				if(directory!=NULL)				{					while((file=readdir(directory))!=NULL) //Read each entry in the directory.					{							if (lstat(file->d_name, &sb) == -1) 						{							perror("stat");						}												 printf("%6ld ", (long) sb.st_ino);						//Display the type of file.						switch (sb.st_mode & S_IFMT) 						{							case S_IFBLK:  printf("b");            								       break;							case S_IFCHR:  printf("c");        								       break;							case S_IFDIR:  printf("d");               								       break;							case S_IFIFO:  printf("p");               								       break;							case S_IFLNK:  printf("l");                 								       break;//.........这里部分代码省略.........
开发者ID:ArihantRJain,项目名称:myShell,代码行数:101,


示例23: parseDomainFile

voidparseDomainFile(AtomPtr file,                DomainPtr **domains_return, regex_t **regex_return){    struct stat ss;    int rc;    if(*domains_return) {        DomainPtr *domain = *domains_return;        while(*domain) {            free(*domain);            domain++;        }        free(*domains_return);        *domains_return = NULL;    }    if(*regex_return) {        regfree(*regex_return);        *regex_return = NULL;    }    if(!file || file->length == 0)        return;    domains = malloc(64 * sizeof(DomainPtr));    if(domains == NULL) {        do_log(L_ERROR, "Couldn't allocate domain list./n");        return;    }    dlen = 0;    dsize = 64;    regexbuf = malloc(512);    if(regexbuf == NULL) {        do_log(L_ERROR, "Couldn't allocate regex./n");        free(domains);        return;    }    rlen = 0;    rsize = 512;    rc = stat(file->string, &ss);    if(rc < 0) {        if(errno != ENOENT)            do_log_error(L_WARN, errno, "Couldn't stat file %s", file->string);    } else {        if(!S_ISDIR(ss.st_mode))            readDomainFile(file->string);        else {            char *fts_argv[2];            FTS *fts;            FTSENT *fe;            fts_argv[0] = file->string;            fts_argv[1] = NULL;            fts = fts_open(fts_argv, FTS_LOGICAL, NULL);            if(fts) {                while(1) {                    fe = fts_read(fts);                    if(!fe) break;                    if(fe->fts_info != FTS_D && fe->fts_info != FTS_DP &&                       fe->fts_info != FTS_DC && fe->fts_info != FTS_DNR)                        readDomainFile(fe->fts_accpath);                }                fts_close(fts);            } else {                do_log_error(L_ERROR, errno,                             "Couldn't scan directory %s", file->string);            }        }    }    if(dlen > 0) {        domains[dlen] = NULL;    } else {        free(domains);        domains = NULL;    }    regex_t *regex;    if(rlen > 0) {        regex = malloc(sizeof(regex_t));        rc = regcomp(regex, regexbuf, REG_EXTENDED | REG_NOSUB);        if(rc != 0) {            char errbuf[100];            regerror(rc, regex, errbuf, 100);            do_log(L_ERROR, "Couldn't compile regex: %s./n", errbuf);            free(regex);            regex = NULL;        }    } else {        regex = NULL;    }    free(regexbuf);    *domains_return = domains;    *regex_return = regex;    return;//.........这里部分代码省略.........
开发者ID:nathantsoi,项目名称:polipo,代码行数:101,


示例24: main

int main(int argc, char *argv[]) {	FILE *fp_infile = NULL, *fp_outfile = NULL, *fp_xmloutfile = NULL, *devnull;#ifdef __MINGW32__	HANDLE fh_infile = NULL;#endif	int c, lastsecond = 0, lastkeyframe = 0, unlink_infile = 0;	char *flv, *infile, *outfile, *xmloutfile, *tempfile, *creator;	unsigned int i;	size_t filesize = 0, streampos, metadatasize;	struct stat sb;	FLVFileHeader_t *flvfileheader;	opterr = 0;	infile = NULL;	outfile = NULL;	xmloutfile = NULL;	tempfile = NULL;	creator = NULL;	while((c = getopt(argc, argv, "i:o:x:t:c:lkh")) != -1) {		switch(c) {			case 'i':				infile = optarg;				break;			case 'o':				outfile = optarg;				break;			case 'x':				xmloutfile = optarg;				break;			case 't':				tempfile = optarg;				break;			case 'c':				creator = optarg;				break;			case 'l':				lastsecond = 1;				break;			case 'k':				lastkeyframe = 1;				break;			case 'h':				print_usage();				exit(1);				break;			case ':':				fprintf(stderr, "The option -%c expects a parameter. -h for help./n", optopt);				exit(1);				break;			case '?':				fprintf(stderr, "Unknown option: -%c. -h for help./n", optopt);				exit(1);				break;			default:				print_usage();				exit(1);				break;		}	}	if(infile == NULL) {		fprintf(stderr, "Please provide an input file. -h for help./n");		exit(1);	}	if(outfile == NULL && xmloutfile == NULL) {		fprintf(stderr, "Please provide at least one output file. -h for help./n");		exit(1);	}	if(tempfile == NULL && !strcmp(infile, "-")) {		fprintf(stderr, "Please specify a temporary file. -h for help./n");		exit(1);	}	// Check input file	if(!strcmp(infile, "-")) {		// Read from stdin		// Check the temporary file		if(outfile != NULL) {			if(!strcmp(tempfile, outfile)) {				fprintf(stderr, "The temporary file and the output file must not be the same./n");				exit(1);			}		}		if(xmloutfile != NULL) {			if(!strcmp(tempfile, xmloutfile)) {				fprintf(stderr, "The temporary file and the XML output file must not be the same./n");				exit(1);			}		}		// Open the temporary file		fp_infile = fopen(tempfile, "wb");		if(fp_infile == NULL) {			fprintf(stderr, "Couldn't open the tempfile %s./n", tempfile);			exit(1);		}//.........这里部分代码省略.........
开发者ID:danielbush,项目名称:fez,代码行数:101,


示例25: command_remove

static int command_remove(args_t * args){	assert(args != NULL);	struct stat st;	if (stat(args->path, &st) != 0) {		ERRNO(errno);		return -1;	}	if (!S_ISREG(st.st_mode)) {		ERRNO(errno);		return -1;	}	FILE *i = fopen(args->path, "r");	if (i == NULL) {		ERRNO(errno);		return -1;	}	FILE *o = fopen(args->file, "w");	if (o == NULL) {		ERRNO(errno);		return -1;	}#define INPUT_SIZE		4086	char input[INPUT_SIZE];	// multiple of 9-bytes#undef INPUT_SIZE	size_t count = 0;	while (count < st.st_size) {		clearerr(i);		size_t rc = fread(input, 1, sizeof input, i);		if (rc == 0) {			int err = ferror(i);			if (err) {				ERRNO(errno);				return -1;			} else				break;		}		count += rc;    char output[(((sizeof input)/(ECC_SIZE+1))*ECC_SIZE) ];		ssize_t removed_size;		if (args->p8 == f_P8)			removed_size =			    p8_ecc_remove_size(output, sizeof output, input, rc);		else			removed_size =			    sfc_ecc_remove(output, sizeof output, input, rc);		if (removed_size < 0) {			ERRNO(errno);			return -1;		}		clearerr(o);		rc = fwrite(output, 1, removed_size, o);		if (rc == 0) {			int err = ferror(o);			if (err) {				ERRNO(errno);				return -1;			}		}	}	if (fclose(i) == EOF) {		ERRNO(errno);		return -1;	}	if (fclose(o) == EOF) {		ERRNO(errno);		return -1;	}	return 0;}
开发者ID:eddiejames,项目名称:ffs,代码行数:84,


示例26: my_mount

/* mounts, creating the device if needed+possible */int my_mount(const char *dev, const char *location, const char *fs, int force_rw){    unsigned long flags = MS_MGC_VAL | (force_rw ? 0 : MS_RDONLY);    char * opts = NULL;    struct stat buf;    int rc;    if (strcmp(fs, "nfs")) {        rc = ensure_dev_exists(dev);        if (rc != 0) {            log_message("could not create required device file");            return -1;        }    }    log_message("mounting %s on %s as type %s", dev, location, fs);    if (stat(location, &buf)) {        if (mkdir(location, 0755)) {            log_perror("could not create location dir");            return -1;        }    } else if (!S_ISDIR(buf.st_mode)) {        log_message("not a dir %s, will unlink and mkdir", location);        if (unlink(location)) {            log_perror("could not unlink");            return -1;        }        if (mkdir(location, 0755)) {            log_perror("could not create location dir");            return -1;        }    }#ifndef DISABLE_MEDIAS    if (!strcmp(fs, "vfat")) {        my_modprobe("nls_cp437", ANY_DRIVER_TYPE, NULL);        my_modprobe("nls_iso8859_1", ANY_DRIVER_TYPE, NULL);        my_modprobe("vfat", ANY_DRIVER_TYPE, NULL);        opts = (char*)"check=relaxed";    }    if (!strcmp(fs, "ntfs")) {        my_modprobe("ntfs", ANY_DRIVER_TYPE, NULL);    }    if (!strcmp(fs, "reiserfs"))        my_modprobe("reiserfs", ANY_DRIVER_TYPE, NULL);    if (!strcmp(fs, "reiser4"))        my_modprobe("reiser4", ANY_DRIVER_TYPE, NULL);    if (!strcmp(fs, "jfs"))        my_modprobe("jfs", ANY_DRIVER_TYPE, NULL);    if (!strcmp(fs, "xfs"))        my_modprobe("xfs", ANY_DRIVER_TYPE, NULL);    if (!strcmp(fs, "ext4"))        my_modprobe("ext4", ANY_DRIVER_TYPE, NULL);    if (!strcmp(fs, "btrfs"))        my_modprobe("btrfs", ANY_DRIVER_TYPE, NULL);#endif    if (!strcmp(fs, "iso9660"))        my_modprobe("isofs", ANY_DRIVER_TYPE, NULL);#ifndef DISABLE_NETWORK    if (!strcmp(fs, "nfs")) {        my_modprobe("nfs", ANY_DRIVER_TYPE, NULL);        log_message("preparing nfsmount for %s", dev);        rc = nfsmount_prepare(dev, &opts);        if (rc != 0)            return rc;    }#endif    rc = mount(dev, location, fs, flags, opts);    if (rc != 0) {        log_perror("mount failed");        rmdir(location);    }    return rc;}
开发者ID:tapwag,项目名称:drakx,代码行数:87,


示例27: do_daemon_work

static int do_daemon_work(const char *channel, const char *sync_shutdown_file,		   unsigned long timeout, unsigned long min_delta,		   int *restartp){    int r = 0;    time_t session_start;    time_t single_start;    int    delta;    struct stat sbuf;    sync_log_reader_t *slr;    *restartp = RESTART_NONE;    slr = sync_log_reader_create_with_channel(channel);    session_start = time(NULL);    while (1) {	single_start = time(NULL);	signals_poll();	/* Check for shutdown file */	if (sync_shutdown_file && !stat(sync_shutdown_file, &sbuf)) {	    unlink(sync_shutdown_file);	    break;	}	/* See if its time to RESTART */	if ((timeout > 0) &&	    ((single_start - session_start) > (time_t) timeout)) {	    *restartp = RESTART_NORMAL;	    break;	}	r = sync_log_reader_begin(slr);	if (r) {	    /* including specifically r == IMAP_AGAIN */	    if (min_delta > 0) {		sleep(min_delta);	    } else {		usleep(100000);    /* 1/10th second */	    }	    continue;	}	/* Process the work log */	if ((r=do_sync(slr))) {	    syslog(LOG_ERR,		   "Processing sync log file %s failed: %s",		   sync_log_reader_get_file_name(slr), error_message(r));	    break;	}	r = sync_log_reader_end(slr);	if (r) break;	delta = time(NULL) - single_start;	if (((unsigned) delta < min_delta) && ((min_delta-delta) > 0))	    sleep(min_delta-delta);    }    sync_log_reader_free(slr);    if (*restartp == RESTART_NORMAL) {	r = do_restart();	if (r) {	    syslog(LOG_ERR, "sync_client RESTART failed: %s",		   error_message(r));	} else {	    syslog(LOG_INFO, "sync_client RESTART succeeded");	}	r = 0;    }    return(r);}
开发者ID:martinpal,项目名称:cyrus-imapd,代码行数:76,


示例28: apprentice_load

/* * parse a file or directory of files * const char *fn: name of magic file or directory */static int apprentice_load(RMagic *ms, struct r_magic **magicp, ut32 *nmagicp, const char *fn, int action) {	ut32 marraycount, i, mentrycount = 0, starttest;	struct r_magic_entry *marray;	char subfn[MAXPATHLEN];	struct dirent *d;	struct stat st;	int errs = 0;	DIR *dir;	ms->flags |= R_MAGIC_CHECK;	/* Enable checks for parsed files */        maxmagic = MAXMAGIS;	if ((marray = calloc (maxmagic, sizeof(*marray))) == NULL) {		file_oomem (ms, maxmagic * sizeof(*marray));		return -1;	}	marraycount = 0;	/* print silly verbose header for USG compat. */	if (action == FILE_CHECK)		eprintf ("%s/n", usg_hdr);	/* load directory or file */	if (stat (fn, &st) == 0 && S_ISDIR (st.st_mode)) {		if (r_sandbox_enable (0) && !r_sandbox_check_path (fn)) {			free (marray);			return  -1;		}		dir = opendir (fn);		if (dir) {			while ((d = readdir (dir))) {				if (*d->d_name=='.') continue;				snprintf (subfn, sizeof (subfn), "%s/%s", fn, d->d_name);				if (stat (subfn, &st) == 0 && S_ISREG (st.st_mode))					load_1 (ms, action, subfn, &errs, &marray, &marraycount);				//else perror (subfn);			}			closedir (dir);		} else errs++;	} else load_1 (ms, action, fn, &errs, &marray, &marraycount);	if (errs)		goto out;	/* Set types of tests */	for (i = 0; i < marraycount; ) {		if (marray[i].mp->cont_level != 0) {			i++;			continue;		}		starttest = i;		do {			set_test_type(marray[starttest].mp, marray[i].mp);			if (ms->flags & R_MAGIC_DEBUG) {				(void)fprintf(stderr, "%s%s%s: %s/n",					marray[i].mp->mimetype,					marray[i].mp->mimetype[0] == '/0' ? "" : "; ",					marray[i].mp->desc[0] ? marray[i].mp->desc : "(no description)",					marray[i].mp->flag & BINTEST ? "binary" : "text");				if (marray[i].mp->flag & BINTEST) {#define SYMBOL "text"#define SYMLEN sizeof(SYMBOL)					char *p = strstr(marray[i].mp->desc, "text");					if (p && (p == marray[i].mp->desc || isspace((unsigned char)p[-1])) &&					    (p + SYMLEN - marray[i].mp->desc == MAXstring ||					     (p[SYMLEN] == '/0' || isspace((unsigned char)p[SYMLEN])))) {						(void)fprintf(stderr,							      "*** Possible binary test for text type/n");					}#undef SYMBOL#undef SYMLEN				}			}		} while (++i < marraycount && marray[i].mp->cont_level != 0);	}	qsort (marray, marraycount, sizeof(*marray), apprentice_sort);	/*	 * Make sure that any level 0 "default" line is last (if one exists).	 */	for (i = 0; i < marraycount; i++) {		if (marray[i].mp->cont_level == 0 &&		    marray[i].mp->type == FILE_DEFAULT) {			while (++i < marraycount)				if (marray[i].mp->cont_level == 0)					break;			if (i != marraycount) {				ms->line = marray[i].mp->lineno; /* XXX - Ugh! */				file_magwarn (ms, "level 0 /"default/" did not sort last");			}			break;		}	}	for (i = 0; i < marraycount; i++)//.........这里部分代码省略.........
开发者ID:AmesianX,项目名称:radare2,代码行数:101,



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


C++ stat64函数代码示例
C++ stasis_message_data函数代码示例
51自学网自学EXCEL、自学PS、自学CAD、自学C语言、自学css3实例,是一个通过网络自主学习工作技能的自学平台,网友喜欢的软件自学网站。
京ICP备13026421号-1