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

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

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

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

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

示例1: PrintTime

void PrintTime(){    time(&rawtime);    timeinfo = localtime(&rawtime);    strftime(time_buffer,64,"%x %H:%M:%S",timeinfo);//"%a %b %d %Y %X %z",timeinfo);    printf(time_buffer);}
开发者ID:weber21w,项目名称:uzebox-weber,代码行数:6,


示例2: strftime

HeapString DateTime::ToString(const StringRef& formaterStr) const{	char s[256];	strftime(s, sizeof(s), formaterStr.c_str(), &mDate);	return HeapString(s);}
开发者ID:fjz13,项目名称:Medusa,代码行数:6,


示例3: get_examine_data_from_table

static BDMDExamineData* get_examine_data_from_table (GHashTable *table, gboolean free_table, GError **error) {    BDMDExamineData *data = g_new0 (BDMDExamineData, 1);    gchar *value = NULL;    gchar *first_space = NULL;    BSSize size = NULL;    BSError *bs_error = NULL;    struct tm tm;    char time_str[20];    gchar *name_str = NULL;    data->level = g_strdup ((gchar*) g_hash_table_lookup (table, "Raid Level"));    if (!(data->level))        /* BUG: mdadm outputs "RAID Level" for some metadata formats (rhbz#1380034) */        data->level = g_strdup ((gchar*) g_hash_table_lookup (table, "RAID Level"));    value = (gchar*) g_hash_table_lookup (table, "Raid Devices");    if (!value)        /* BUG: mdadm outputs "RAID Devices" for some metadata formats (rhbz#1380034) */        value = (gchar*) g_hash_table_lookup (table, "RAID Devices");    if (value)        data->num_devices = g_ascii_strtoull (value, NULL, 0);    else        data->num_devices = 0;    name_str = ((gchar*) g_hash_table_lookup (table, "Name"));    if (name_str) {        g_strstrip (name_str);        first_space = strchr (name_str, ' ');        if (first_space)            *first_space = '/0';        data->name = g_strdup (name_str);    }    value = (gchar*) g_hash_table_lookup (table, "Array Size");    if (value) {        first_space = strchr (value, ' ');        if (first_space)            *first_space = '/0';        if (value && first_space)            /* Array Size is in KiB */            data->size = g_ascii_strtoull (value, NULL, 0) * 1024;    } else        data->size = 0;    data->uuid = g_strdup ((gchar*) g_hash_table_lookup (table, "Array UUID"));    if (!data->uuid)        /* also try just "UUID" which may be reported e.g for IMSM FW RAID */        data->uuid = g_strdup ((gchar*) g_hash_table_lookup (table, "UUID"));    value = (gchar*) g_hash_table_lookup (table, "Update Time");    if (value) {        memset(&tm, 0, sizeof(struct tm));        strptime(value, "%a %b %e %H:%M:%S %Y", &tm);        strftime(time_str, sizeof(time_str), "%s" , &tm);        data->update_time = g_ascii_strtoull (time_str, NULL, 0);    } else        data->update_time = 0;    data->dev_uuid = g_strdup ((gchar*) g_hash_table_lookup (table, "Device UUID"));    value = (gchar*) g_hash_table_lookup (table, "Events");    if (value)        data->events = g_ascii_strtoull (value, NULL, 0);    else        data->events = 0;    value = (gchar*) g_hash_table_lookup (table, "Version");    if (value)        data->metadata = g_strdup (value);    else        data->metadata = NULL;    value = (gchar*) g_hash_table_lookup (table, "Chunk Size");    if (value) {        size = bs_size_new_from_str (value, &bs_error);        if (size) {            data->chunk_size = bs_size_get_bytes (size, NULL, &bs_error);            bs_size_free (size);        }        if (bs_error) {            g_set_error (error, BD_MD_ERROR, BD_MD_ERROR_PARSE,                         "Failed to parse chunk size from mdexamine data: %s", bs_error->msg);            bs_clear_error (&bs_error);        }    } else        data->chunk_size = 0;    if (free_table)        g_hash_table_destroy (table);    return data;}
开发者ID:cathay4t,项目名称:libblockdev,代码行数:94,


示例4: read_request

/* Here is the deal, we read as much as we can into the empty buffer, then * reset the buffer pointer to the end of the read material and append at * next read */voidread_request( struct cn_strct *cn ){	char *next;	int   num_recv;	time_t     now = time(NULL);	struct tm *tm_struct;	/* FIXME: For now assume that RECV_BUFF_LENGTH is enough for one read */	num_recv = recv(		cn->net_socket,		cn->data_buf,		RECV_BUFF_LENGTH - cn->processed_bytes,		//MAX_READ_LENGTH,		0	);	// sanity check	if (num_recv <= 0) {		if (num_recv <= 0)         /* really dead? */			remove_conn_from_list(cn);		return;	}	// set the read pointer to where we left off	next = cn->data_buf_head + cn->processed_bytes;	// adjust buffer	cn->processed_bytes += num_recv;	cn->data_buf = cn->data_buf_head + cn->processed_bytes;	/* null terminate the current buffer -> overwrite on next read */	cn->data_buf_head[cn->processed_bytes] = '/0';	/* a naive little line parser */	while ( (*next != '/0') ) {		if ( *(next)=='/r')			if (*(next+1)=='/n' &&			    *(next+2)=='/r' && *(next+3)=='/n' ) {			/* proceed next stage			   prepare the global date string */				if (now-_Last_loop>0) {					_Last_loop = now;					tm_struct = gmtime(&_Last_loop);					//Sun, 06 Nov 1994 08:49:37 GMT					strftime( _Master_date, 30, "%a, %d %b %Y %H:%M:%S %Z", tm_struct);				}				cn->req_state = REQSTATE_BUFF_HEAD;				/* enqueue this connection to the _App_queue */				pthread_mutex_lock( &pull_job_mutex );				if (NULL == _Queue_tail) {					_Queue_tail = _Queue_head = cn;					_Queue_count = 1;				}				else {					_Queue_tail->q_prev = cn;					_Queue_tail = cn;					_Queue_count++;				}				pthread_mutex_unlock( &pull_job_mutex );				/* wake a worker to start the application */				pthread_cond_signal (&wake_worker_cond);			}		next++;	}}
开发者ID:childhood,项目名称:parcle,代码行数:75,


示例5: onion_shortcut_date_string

/** * @short Transforms a time_t to a RFC 822 date string *  * This date format is the standard in HTTP protocol as RFC 2616, section 3.3.1 *  * The dest pointer must be at least 32 bytes long as thats the maximum size of the date. */void onion_shortcut_date_string(time_t t, char *dest){	struct tm ts;	gmtime_r(&t, &ts);	strftime(dest, t, "%a, %d %b %Y %T %Z", &ts);}
开发者ID:cemonds,项目名称:onion,代码行数:12,


示例6: OutputDebugStringA

// Credit to NTAuthorityLONG WINAPI DumpHandler::CustomUnhandledExceptionFilter(LPEXCEPTION_POINTERS ExceptionInfo){	// Ignore breakpoints.	if (ExceptionInfo->ExceptionRecord->ExceptionCode == EXCEPTION_BREAKPOINT) return EXCEPTION_CONTINUE_EXECUTION;	// Try skipping exceptions	/* Disable that, it seems unsafe	if ((ExceptionInfo->ExceptionRecord->ExceptionFlags & EXCEPTION_NONCONTINUABLE) != EXCEPTION_NONCONTINUABLE)	{		OutputDebugStringA(hString::va("New exception at 0x%X, try ignoring it...", ExceptionInfo->ExceptionRecord->ExceptionAddress));		ExceptionInfo->ExceptionRecord->ExceptionFlags |= EXCEPTION_NONCONTINUABLE;		return EXCEPTION_CONTINUE_EXECUTION;	}	else	{		OutputDebugStringA("Ignoring failed. Handling it now...");	}	*/	// step 1: write minidump	char error[1024];	char filename[MAX_PATH];	__time64_t time;	tm* ltime;	_time64(&time);	ltime = _localtime64(&time);	strftime(filename, sizeof(filename) - 1, "Redacted - %H-%M-%S %d.%m.%Y.dmp", ltime);	_snprintf(error, sizeof(error) - 1, "A minidump has been written to %s.", filename);	HANDLE hFile = CreateFile(filename, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);	if (hFile != INVALID_HANDLE_VALUE)	{		MINIDUMP_EXCEPTION_INFORMATION ex = { 0 };		ex.ThreadId = GetCurrentThreadId();		ex.ExceptionPointers = ExceptionInfo;		ex.ClientPointers = FALSE;		MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hFile, MiniDumpNormal, &ex, NULL, NULL);		CloseHandle(hFile);	}	else	{		_snprintf(error, sizeof(error) - 1, "An error (0x%x) occurred during creating %s.", GetLastError(), filename);	}	// step 2: exit the application	// why was this removed?	if (ExceptionInfo->ExceptionRecord->ExceptionCode == EXCEPTION_STACK_OVERFLOW)	{		MessageBox(0, "Termination because of a stack overflow.", "ERROR", MB_ICONERROR);	}	else	{		MessageBox(0, hString::va("Fatal error (0x%08x) at 0x%08x./n%s", ExceptionInfo->ExceptionRecord->ExceptionCode, ExceptionInfo->ExceptionRecord->ExceptionAddress, error), "ERROR", MB_ICONERROR);	}	TerminateProcess(GetCurrentProcess(), ExceptionInfo->ExceptionRecord->ExceptionCode);	return 0;}
开发者ID:RaptorFactor,项目名称:SteamBase,代码行数:63,


示例7: main

/** * @brief Start the storage server. * * This is the main entry point for the storage server.  It reads the * configuration file, starts listening on a port, and proccesses * commands from clients. */int main(int argc, char *argv[]){	Table database[MAX_DATABASE_LEN];	//printf("Setting time/n");//remove	  time ( &rawtime );	  timeinfo2 = localtime ( &rawtime );	  //printf("Finished rawtime stuff/n"); //remove	  //printf("About to do strftime/n"); //remove	  strftime (buffer2,40,"Server-%Y-%m-%d-%H-%M-%S.log",timeinfo2);	  puts (buffer2);	  //printf("Finished setting time/n");//remove	// Process command line arguments.	// This program expects exactly one argument: the config file name.	assert(argc > 0);	if (argc != 2) {		printf("Usage %s <config_file>/n", argv[0]);		exit(EXIT_FAILURE);	}	char *config_file = argv[1];	// Read the config file.	struct config_params params;	int status = read_config(config_file, &params);	if (status != 0) {		printf("Error processing config file./n");		exit(EXIT_FAILURE);	}	n = sprintf(message, "Server on %s:%d/n", params.server_host, params.server_port);	//printf("%i", n);	fp = fopen(buffer2, "a+");	logger(LOGGING, fp, message);	fclose(fp);	// Create a socket.	int listensock = socket(PF_INET, SOCK_STREAM, 0);	if (listensock < 0) {		printf("Error creating socket./n");		exit(EXIT_FAILURE);	}	// Allow listening port to be reused if defunct.	int yes = 1;	status = setsockopt(listensock, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof yes);	if (status != 0) {		printf("Error configuring socket./n");		exit(EXIT_FAILURE);	}	// Bind it to the listening port.	struct sockaddr_in listenaddr;	memset(&listenaddr, 0, sizeof listenaddr);	listenaddr.sin_family = AF_INET;	listenaddr.sin_port = htons(params.server_port);	inet_pton(AF_INET, params.server_host, &(listenaddr.sin_addr)); // bind to local IP address	status = bind(listensock, (struct sockaddr*) &listenaddr, sizeof listenaddr);	if (status != 0) {		printf("Error binding socket./n");		exit(EXIT_FAILURE);	}	// Listen for connections.	status = listen(listensock, MAX_LISTENQUEUELEN);	if (status != 0) {		printf("Error listening on socket./n");		exit(EXIT_FAILURE);	}	// Listen loop.	int wait_for_connections = 1;	while (wait_for_connections) {		// Wait for a connection.		struct sockaddr_in clientaddr;		socklen_t clientaddrlen = sizeof clientaddr;		int clientsock = accept(listensock, (struct sockaddr*)&clientaddr, &clientaddrlen);		if (clientsock < 0) {			printf("Error accepting a connection./n");			exit(EXIT_FAILURE);		}		n = sprintf(message, "Got a connection from %s:%d./n", inet_ntoa(clientaddr.sin_addr), clientaddr.sin_port);		fp = fopen(buffer2, "a+");		logger(LOGGING, fp, message);		fclose(fp);		// Get commands from client.		int wait_for_commands = 1;		do {			// Read a line from the client.//.........这里部分代码省略.........
开发者ID:cykamancer,项目名称:workspace,代码行数:101,


示例8: calculate_speed

static void calculate_speed(struct progress_bar *prog, unsigned long long copied, unsigned long long current, int done, prog_stat_t *prog_stat){    char *format = "%H:%M:%S";    uint64_t speedps = 1;    uint64_t speed = 1;    double dspeed = 1.0;    float percent = 1.0;    time_t remained;    time_t elapsed;    char Rformated[12], Eformated[12];    char speed_unit[] = "    ";    struct tm *Rtm, *Etm;    uint64_t gbyte=1000000000.0;    uint64_t mbyte=1000000;    uint64_t kbyte=1000;    percent  = prog->unit * copied;    if (percent <= 0)	percent = 1;    else if (percent >= 100)	percent = 99.99;    elapsed  = (time(0) - prog->initial_time);    if (elapsed <= 0)	elapsed = 1;    speedps  = prog->block_size * copied / elapsed;    speed = speedps * 60.0;    prog_stat->percent   = percent;    if (speed >= gbyte){	dspeed = (double)speed / (double)gbyte;	strncpy(speed_unit, "GB", 3);	strncpy(prog_stat->speed_unit, speed_unit, 3);    }else if (speed >= mbyte){	dspeed = (double)speed / (double)mbyte;	strncpy(speed_unit, "MB", 3);	strncpy(prog_stat->speed_unit, speed_unit, 3);    }else if (speed >= kbyte){	dspeed = (double)speed / (double)kbyte;	strncpy(speed_unit, "KB", 3);	strncpy(prog_stat->speed_unit, speed_unit, 3);    }else{	dspeed = speed;	strncpy(speed_unit, "byte", 5);	strncpy(prog_stat->speed_unit, speed_unit, 5);    }    prog_stat->total_percent = prog->total_unit * current;    prog_stat->speed     = dspeed;    if (done != 1){        remained = (time_t)((elapsed/percent*100) - elapsed);	if ((unsigned int)remained > 86400){	    snprintf(Rformated, sizeof(Rformated), " > %3i hrs ", ((int)remained/3600));	}else{	    Rtm = gmtime(&remained);	    strftime(Rformated, sizeof(Rformated), format, Rtm);	}	if ((unsigned int)elapsed > 86400){	    snprintf(Eformated, sizeof(Eformated), " > %3i hrs ", ((int)elapsed/3600));	}else{	    Etm = gmtime(&elapsed);	    strftime(Eformated, sizeof(Eformated), format, Etm);	}    } else {        prog_stat->percent=100;        remained = (time_t)0;        Rtm = gmtime(&remained);	strftime(Rformated, sizeof(Rformated), format, Rtm);	if ((unsigned int)elapsed > 86400){	    snprintf(Eformated, sizeof(Eformated), " > %3i hrs ", ((int)elapsed/3600));	}else{	    Etm = gmtime(&elapsed);	    strftime(Eformated, sizeof(Eformated), format, Etm);	}    }    strncpy(prog_stat->Eformated, Eformated, sizeof(prog_stat->Eformated));    strncpy(prog_stat->Rformated, Rformated, sizeof(prog_stat->Rformated));}
开发者ID:Thomas-Tsai,项目名称:partclone,代码行数:87,


示例9: bsodFatal

void bsodFatal(const char *component){	/* show no more than one bsod while shutting down/crashing */	if (bsodhandled) return;	bsodhandled = true;	std::string lines = getLogBuffer();		/* find python-tracebacks, and extract "  File "-strings */	size_t start = 0;	std::string crash_emailaddr = CRASH_EMAILADDR;	std::string crash_component = "enigma2";	if (component)		crash_component = component;	else	{		while ((start = lines.find("/n  File /"", start)) != std::string::npos)		{			start += 9;			size_t end = lines.find("/"", start);			if (end == std::string::npos)				break;			end = lines.rfind("/", end);				/* skip a potential prefix to the path */			unsigned int path_prefix = lines.find("/usr/", start);			if (path_prefix != std::string::npos && path_prefix < end)				start = path_prefix;			if (end == std::string::npos)				break;			std::string filename(lines.substr(start, end - start) + INFOFILE);			std::ifstream in(filename.c_str());			if (in.good()) {				std::getline(in, crash_emailaddr) && std::getline(in, crash_component);				in.close();			}		}	}	FILE *f;	std::string crashlog_name;	std::ostringstream os;	os << "/media/hdd/enigma2_crash_";	os << time(0);	os << ".log";	crashlog_name = os.str();	f = fopen(crashlog_name.c_str(), "wb");	if (f == NULL)	{		/* No hardisk. If there is a crash log in /home/root, leave it		 * alone because we may be in a crash loop and writing this file		 * all night long may damage the flash. Also, usually the first		 * crash log is the most interesting one. */		crashlog_name = "/home/root/enigma2_crash.log";		if ((access(crashlog_name.c_str(), F_OK) == 0) ||		    ((f = fopen(crashlog_name.c_str(), "wb")) == NULL))		{			/* Re-write the same file in /tmp/ because it's expected to			 * be in RAM. So the first crash log will end up in /home			 * and the last in /tmp */			crashlog_name = "/tmp/enigma2_crash.log";			f = fopen(crashlog_name.c_str(), "wb");		}	}	if (f)	{		time_t t = time(0);		struct tm tm;		char tm_str[32];		localtime_r(&t, &tm);		strftime(tm_str, sizeof(tm_str), "%a %b %_d %T %Y", &tm);		XmlGenerator xml(f);		xml.open("BlakHole");		xml.open("enigma2");		xml.string("crashdate", tm_str);		xml.string("compiledate", __DATE__);		xml.string("contactemail", crash_emailaddr);		xml.comment("Please email this crashlog to above address");		xml.string("skin", getConfigString("config.skin.primary_skin", "Default Skin"));		xml.string("sourcedate", enigma2_date);		xml.string("branch", enigma2_branch);		xml.string("rev", enigma2_rev);		xml.string("version", PACKAGE_VERSION);		xml.close();		xml.open("image");		if(access("/proc/stb/info/boxtype", F_OK) != -1) {			xml.stringFromFile("stbmodel", "/proc/stb/info/boxtype");		}		else if (access("/proc/stb/info/vumodel", F_OK) != -1) {//.........这里部分代码省略.........
开发者ID:kingvuplus,项目名称:rr,代码行数:101,


示例10: date_time_layer_format_time

void date_time_layer_format_time(    char* buffer, size_t buffer_length, struct tm* now, bool is_24h) {    strftime(buffer, buffer_length, is_24h ? "%H:%M" : "%I:%M", now);}
开发者ID:kylewlacy,项目名称:futura-weather,代码行数:5,


示例11: main

int main(int argc, char** argv){	int quadrant_line, quadrant_column;		char *videoFileName = argv[1];	char quadFileName[64];	int i = 0, k, j;	long unsigned int inc = 0;	long unsigned int incaudio = 0;	int videoStreamIndex;	int audioStreamIndex= -1;	int frameFinished, gotPacket;	AVDictionary	*codecOptions = NULL;		UDP_PTSframe_t PTS_frame;	struct tm *start_time_tm;	char start_time_str[64];	long unsigned int start_time;	time_t start_timer_t;		//Crop env	int tam_quad;	int frist = 1, marginLeft = 0, marginTop = 0;	int width , height;    if(argc < 4){        usage();            return -1;    }    signal (SIGTERM, handlerToFinish);	signal (SIGINT, handlerToFinish);    tam_quad = sqrt(amount_of_quadrants);    quadrant_line = atoi(argv[2]);    quadrant_column = atoi(argv[3]);    amount_of_quadrants = (quadrant_line * quadrant_column) + 1;    strcpy (quadFileName, argv[4]);    //Allocat output streams context    ff_output = malloc (sizeof(ff_output_t) * amount_of_quadrants);	av_register_all();	avformat_network_init();	//Initialize Input	if (avformat_open_input (&ff_input.formatCtx, videoFileName, NULL, NULL) != 0) {		printf ("Cold not open input video file at %s/n", videoFileName);		return -1;	}	if (avformat_find_stream_info(ff_input.formatCtx, NULL) < 0) {		printf ("Cold not get stream info/n");		return -1;	}	av_dump_format(ff_input.formatCtx, 0, videoFileName, 0);	videoStreamIndex = av_find_best_stream(ff_input.formatCtx, AVMEDIA_TYPE_VIDEO, -1, -1, &ff_input.encoder, 0);	if (videoStreamIndex < 0) {		printf ("no video streams found/n");		return -1;	}	audioStreamIndex = av_find_best_stream(ff_input.formatCtx, AVMEDIA_TYPE_AUDIO, -1, -1, &ff_input.audioencoder, 0);    if (audioStreamIndex < 0) {        printf ("no audio streams found/n");        return -1;    }    printf ("VIDEO ST %d, AUDIO ST %d/n", videoStreamIndex, audioStreamIndex);    ff_input.audiocodecCtx = ff_input.formatCtx->streams[audioStreamIndex]->codec;	ff_input.codecCtx = ff_input.formatCtx->streams[videoStreamIndex]->codec;	if (avcodec_open2 (ff_input.audiocodecCtx, ff_input.audioencoder, NULL) < 0) {        printf ("Could not open input codec/n");        return -1;    }	if (avcodec_open2 (ff_input.codecCtx, ff_input.encoder, NULL) < 0) {		printf ("Could not open input codec/n");		return -1;	}	//Get system time and append as metadata	getSystemTime (&PTS_frame.frameTimeVal); //Must be the same for all output contexts	start_time = PTS_frame.frameTimeVal.tv_sec;	start_timer_t = (time_t) start_time;	start_time_tm = localtime (&start_timer_t);	strftime(start_time_str, sizeof start_time_str, "%Y-%m-%d %H:%M:%S", start_time_tm);	if (avformat_alloc_output_context2(&formatCtx, NULL, AV_OUTPUT_FORMAT, quadFileName) < 0) {			printf ("could not create output context/n");			return -1;	}//.........这里部分代码省略.........
开发者ID:reny122010,项目名称:Jack-with-ffmpeg,代码行数:101,


示例12: Server

void CPlayer::Reset(){	m_DieTick = Server()->Tick();	m_JoinTick = Server()->Tick();	if (m_pCharacter)		delete m_pCharacter;	m_pCharacter = 0;	m_KillMe = 0;	m_SpectatorID = SPEC_FREEVIEW;	m_LastActionTick = Server()->Tick();	m_TeamChangeTick = Server()->Tick();	m_WeakHookSpawn = false;	int* idMap = Server()->GetIdMap(m_ClientID);	for (int i = 1;i < VANILLA_MAX_CLIENTS;i++)	{		idMap[i] = -1;	}	idMap[0] = m_ClientID;	// DDRace	m_LastCommandPos = 0;	m_LastPlaytime = time_get();	m_Sent1stAfkWarning = 0;	m_Sent2ndAfkWarning = 0;	m_ChatScore = 0;	m_EyeEmote = true;	m_TimerType = g_Config.m_SvDefaultTimerType;	m_DefEmote = EMOTE_NORMAL;	m_Afk = false;	m_LastWhisperTo = -1;	m_LastSetSpectatorMode = 0;	m_TimeoutCode[0] = '/0';	m_TuneZone = 0;	m_TuneZoneOld = m_TuneZone;	m_Halloween = false;	m_FirstPacket = true;	m_SendVoteIndex = -1;	if (g_Config.m_SvEvents)	{		time_t rawtime;		struct tm* timeinfo;		char d[16], m[16], y[16];		int dd, mm;		time ( &rawtime );		timeinfo = localtime ( &rawtime );		strftime (d,sizeof(y),"%d",timeinfo);		strftime (m,sizeof(m),"%m",timeinfo);		strftime (y,sizeof(y),"%Y",timeinfo);		dd = atoi(d);		mm = atoi(m);		if ((mm == 12 && dd == 31) || (mm == 1 && dd == 1))		{ // New Year			m_DefEmote = EMOTE_HAPPY;		}		else if ((mm == 10 && dd == 31) || (mm == 11 && dd == 1))		{ // Halloween			m_DefEmote = EMOTE_ANGRY;			m_Halloween = true;		}		else		{			m_DefEmote = EMOTE_NORMAL;		}	}	m_DefEmoteReset = -1;	GameServer()->Score()->PlayerData(m_ClientID)->Reset();	m_ClientVersion = VERSION_VANILLA;	m_ShowOthers = g_Config.m_SvShowOthersDefault;	m_ShowAll = g_Config.m_SvShowAllDefault;	m_SpecTeam = 0;	m_NinjaJetpack = false;	m_Paused = PAUSED_NONE;	m_DND = false;	m_NextPauseTick = 0;	// Variable initialized:	m_Last_Team = 0;#if defined(CONF_SQL)	m_LastSQLQuery = 0;#endif	int64 Now = Server()->Tick();	int64 TickSpeed = Server()->TickSpeed();	// If the player joins within ten seconds of the server becoming	// non-empty, allow them to vote immediately. This allows players to	// vote after map changes or when they join an empty server.	//	// Otherwise, block voting for 60 seconds after joining.	if(Now > GameServer()->m_NonEmptySince + 10 * TickSpeed)		m_FirstVoteTick = Now + g_Config.m_SvJoinVoteDelay * TickSpeed;	else//.........这里部分代码省略.........
开发者ID:Chairn,项目名称:ddnet,代码行数:101,


示例13: peek_report

static voidpeek_report(const struct peak_packet *packet, const struct peak_track *flow,    const timeslice_t *timer){	unsigned int i;	for (i = 0; i < use_count; ++i) {		if (i) {			pout(", ");		}		switch (use_print[i]) {		case USE_APP:			pout("app: %s",			    peak_li_name(peak_li_merge(flow->li)));			break;		case USE_APP_LEN:			pout("app_len: %hu", packet->app_len);			break;		case USE_FLOW:			pout("flow: %llu", (unsigned long long)flow->id);			break;		case USE_IP_LEN:			pout("ip_len: %hu", packet->net_len);			break;		case USE_IP_TYPE:			pout("ip_type: %hhu", packet->net_type);			break;		case USE_SRC:			if (packet->net_family == AF_INET6 &&			    packet->flow_sport) {				pout("src: [%s]%s",				    netprint(&packet->net_saddr),				    portprint(packet->flow_sport));			} else {				pout("src: %s%s",				    netprint(&packet->net_saddr),				    portprint(packet->flow_sport));			}			break;		case USE_DST:			if (packet->net_family == AF_INET6 &&			    packet->flow_dport) {				pout("dst: [%s]%s",				    netprint(&packet->net_daddr),				    portprint(packet->flow_dport));			} else {				pout("dst: %s%s",				    netprint(&packet->net_daddr),				    portprint(packet->flow_dport));			}			break;		case USE_TIME: {			char tsbuf[40];			pout("time: %s.%06ld", strftime(tsbuf, sizeof(tsbuf),			    OUTPUT_TIME, &timer->gmt) ? tsbuf : "????",			    timer->tv.tv_usec);			break;		}		default:			break;		}	}	pout("/n");}
开发者ID:anthcp,项目名称:libpeak,代码行数:66,


示例14: main

int main(int argc, char* argv[]){    DIR *mydir;    struct dirent *myfile;    struct stat mystat;    struct passwd *usr;    struct group *grp;    struct tm *tme;    char buf[512];    char fileperm[512];    char tmbuf[100];    	if(argv[1]==NULL){  		perror("usage ./a.out file/directory_name/n");  		exit(0);  	}  	  	if((mydir = opendir(argv[1]))==NULL){  		perror("no such file or directory/n");  		exit(0);  	}  			usr=getpwuid(mystat.st_mode);    grp=getgrgid(mystat.st_mode);    while((myfile = readdir(mydir)) != NULL){            sprintf(buf, "%s/%s", argv[1], myfile->d_name);   //appends the filename with the path    		if((lstat(buf, &mystat))<0){    			perror("stat error/n");    		}      			 	    switch (mystat.st_mode & S_IFMT) {        	    case S_IFDIR:  printf("d ");            break;        		case S_IFREG:  printf("r ");            break;        		default:       printf("- ");            break;    		}    		    		tme=localtime(&mystat.st_mtime);    		strftime(tmbuf,sizeof(tmbuf),"%A %B %H:%M:%S",tme);    		     		sprintf(fileperm,"%c%c%c%c%c%c%c%c%c",    		(mystat.st_mode)& S_IRUSR ? 'r':'-',    		(mystat.st_mode)& S_IWUSR ? 'w':'-',    		(mystat.st_mode)& S_IXUSR ? 'x':'-',    		(mystat.st_mode)& S_IRGRP ? 'r':'-',    		(mystat.st_mode)& S_IRGRP ? 'w':'-',    		(mystat.st_mode)& S_IXGRP ? 'x':'-',    		(mystat.st_mode)& S_IROTH ? 'r':'-',    		(mystat.st_mode)& S_IWOTH ? 'w':'-',    		(mystat.st_mode)& S_IXOTH ? 'x':'-'    		);    		    		printf("%s ",fileperm);    		printf("%d ",mystat.st_nlink);    		printf("%s ",usr->pw_name);    		printf("%s ",grp->gr_name);    		printf("%s",tmbuf);    		printf("%d ",mystat.st_size);    		printf("%s/n", myfile->d_name);            	}    	closedir(mydir);	return 0;}
开发者ID:AthiraLekshmiCV,项目名称:Systems-Programming,代码行数:67,


示例15: gopher_menu

//.........这里部分代码省略.........		}		/* Handle directories */		if ((dir[i].mode & S_IFMT) == S_IFDIR) {			/* Check for a gophertag */			snprintf(buf, sizeof(buf), "%s/%s",				pathname, st->tag_file);			if (stat(buf, &file) == OK &&			    (file.st_mode & S_IFMT) == S_IFREG) {				/* Use the gophertag as displayname */				if ((fp = fopen(buf , "r"))) {					fgets(buf, sizeof(buf), fp);					chomp(buf);					fclose(fp);					/* Skip empty gophertags */					if (*buf) {						/* Convert to output charset */						if (st->opt_iconv) sstrniconv(st->out_charset, displayname, buf);						else sstrlcpy(displayname, buf);					}				}			}			/* Dir listing with dates */			if (st->opt_date) {				ltime = localtime(&dir[i].mtime);				strftime(timestr, sizeof(timestr), DATE_FORMAT, ltime);				/* Hack to get around UTF-8 byte != char */				n = width - strcut(displayname, width);				strrepeat(buf, ' ', n);				printf("1%s%s   %s        -  /t%s%s//t%s/t%i" CRLF,					displayname,					buf,					timestr,					st->req_selector,					encodedname,					st->server_host,					st->server_port);			}			/* Regular dir listing */			else {				strcut(displayname, st->out_width);				printf("1%s/t%s%s//t%s/t%i" CRLF,					displayname,					st->req_selector,					encodedname,					st->server_host,					st->server_port);			}			continue;		}		/* Skip special files (sockets, fifos etc) */		if ((dir[i].mode & S_IFMT) != S_IFREG) continue;
开发者ID:graydon,项目名称:gophernicus,代码行数:66,


示例16: popc_logger_t

int popc_logger_t(LOGLEVEL level, const char* file, int line, const char* function, const char* tag, const char* format,                  ...) {    // Check if message level in higher than our threshold    if (level < MIN_LOG_LEVEL)        return 0;    // Use file name without path to avoid having the full user path in logs    const char* basename = strrchr(file, '/');    if (basename == nullptr)        basename = file;    else        basename += 1;    auto log_file = get_log_file();    // Time    time_t rawtime;    time(&rawtime);    const tm* timeinfo = localtime(&rawtime);    char dd[20];    strftime(dd, sizeof(dd), "%Y-%m-%d %H:%M:%S", timeinfo);    char msg[512];    va_list ap;    va_start(ap, format);    vsnprintf(msg, sizeof(msg), format, ap);    va_end(ap);    auto msg_length = strlen(msg);    if (msg[msg_length - 1] == '/n') {        msg[msg_length - 1] = ' ';    }    // Print the message to stderr or stdout    if (level >= MIN_STDERR_LEVEL)        if (tag) {            fprintf(stderr, "%s %5d %s [%5s] %s (%s:%d %s)/n", dd, getpid(), get_prefix(level), tag, msg, basename,                    line, function);        } else {            fprintf(stderr, "%s %5d %s %s (%s:%d %s)/n", dd, getpid(), get_prefix(level), msg, basename, line,                    function);        }    else if (level >= MIN_STDOUT_LEVEL)        fprintf(stdout, "%s/n", msg);    // Print the message to file    FILE* f = fopen(log_file.c_str(), "a");    if (f == NULL) {        fprintf(stderr, "ERROR: Impossible to open log file %s/n", log_file.c_str());        return 1;    }    if (tag) {        fprintf(f, "%s %5d %s [%5s] %s (%s:%d %s)/n", dd, getpid(), get_prefix(level), tag, msg, basename, line,                function);    } else {        fprintf(f, "%s %5d %s %s (%s:%d %s)/n", dd, getpid(), get_prefix(level), msg, basename, line, function);    }    fclose(f);    return 0;}
开发者ID:jacklicn,项目名称:pop-cpp,代码行数:62,


示例17: _MIN

//.........这里部分代码省略.........    payload_loc[Y] = _cg_loc[Y];    payload_loc[Z] = _cg_loc[Z];    _payload -= _empty_weight;//***** SYSTEMS ***************************************    for (unsigned i=0; i<systems.size(); ++i)    {        if (systems[i]->enabled()) {            systems[i]->set(_cg_loc);        }    }//***** COEFFICIENTS **********************************    aircraft->set_lift();    aircraft->set_drag();    aircraft->set_side();    aircraft->set_roll();    aircraft->set_pitch();    aircraft->set_yaw();//************************************************//*                                              *//*  Print out xml document                      *//*                                              *//************************************************    char str[64];    time_t t;    time(&t);#ifdef _MSC_VER    struct tm ti;    localtime_s(&ti, &t);    strftime(str, sizeof(str), "%d %b %Y", &ti);#else    struct tm *ti= localtime(&t);    strftime(str, sizeof(str), "%d %b %Y", ti);#endif    _dir = _subdir ? create_dir(_path, _name) : _path;    if (_dir.empty()) {        std::cout << "Unable to create directory: " << _path << "/" << _name << std::endl;        return false;    }    std::string systems_dir;    if (_system_files)    {        systems_dir = create_dir(_dir, "Systems");        if (systems_dir.empty())        {            std::cout << "Unable to create directory: " << _dir<< "/Systems" << std::endl;            _system_files = false;        }    }    std::string fname = _dir + "/" + std::string(_name) + ".xml";    std::string version = AEROMATIC_VERSION_STR;    if (!_overwrite && overwrite(fname)) {        std::cout << "File already exists: " << fname << std::endl;        return false;    }    std::ofstream file;
开发者ID:AEgisTG,项目名称:jsbsim,代码行数:67,


示例18: pre

    void pre(std::ostream& out, Actions& actions)    {        // The quickbook file has been parsed. Now, it's time to        // generate the output. Here's what we'll do *before* anything else.        if (actions.doc_id.empty())            actions.doc_id = detail::make_identifier(                actions.doc_title.begin(),actions.doc_title.end());        if (actions.doc_dirname.empty())            actions.doc_dirname = actions.doc_id;        if (actions.doc_last_revision.empty())        {            // default value for last-revision is now            char strdate[ 30 ];            time_t t = time(0);            strftime(                strdate, sizeof(strdate),                "$" /* prevent CVS substitution */ "Date: %Y/%m/%d %H:%M:%S $",                gmtime(&t)            );            actions.doc_last_revision = strdate;        }        out << "<?xml version=/"1.0/" encoding=/"UTF-8/"?>/n"            << "<!DOCTYPE library PUBLIC /"-//Boost//DTD BoostBook XML V1.0//EN/"/n"            << "     /"http://www.boost.org/tools/boostbook/dtd/boostbook.dtd/">/n"            << '<' << actions.doc_type << "/n"            << "    id=/"" << actions.doc_id << "/"/n"            << "    name=/"" << actions.doc_title << "/"/n"            << "    dirname=/"" << actions.doc_dirname << "/"/n"            << "    last-revision=/"" << actions.doc_last_revision << "/" /n"            << "    xmlns:xi=/"http://www.w3.org/2001/XInclude/">/n"            << "  <" << actions.doc_type << "info>/n";        for_each(            actions.doc_authors.begin()          , actions.doc_authors.end()          , xml_author(out));        if (!actions.doc_copyright_holder.empty())        {            out << "/n" << "    <copyright>/n";            for_each(                actions.doc_copyright_years.begin()              , actions.doc_copyright_years.end()              , xml_year(out));            out << "      <holder>" << actions.doc_copyright_holder << "</holder>/n"                << "    </copyright>/n"                << "/n"            ;        }        if (!actions.doc_license.empty())        {            out << "    <legalnotice>/n"                << "      <para>/n"                << "        " << actions.doc_license << "/n"                << "      </para>/n"                << "    </legalnotice>/n"                << "/n"            ;        }        if (!actions.doc_purpose.empty())        {            out << "    <" << actions.doc_type << "purpose>/n"                << "      " << actions.doc_purpose                << "    </" << actions.doc_type << "purpose>/n"                << "/n"            ;        }        if (!actions.doc_purpose.empty())        {            out << "    <" << actions.doc_type << "category name=/"category:"                << actions.doc_category                << "/"></" << actions.doc_type << "category>/n"                << "/n"            ;        }        out << "  </" << actions.doc_type << "info>/n"            << "/n"        ;        if (!actions.doc_title.empty())        {            out << "  <title>" << actions.doc_title;            if (!actions.doc_version.empty())                out << ' ' << actions.doc_version;            out << "</title>/n/n/n";        }    }
开发者ID:AndroidAppList,项目名称:Android-Supertux,代码行数:99,


示例19: Panic

void Logger::logPrint( bool hex, const char * const file, const int line, const int level, const char *fstring, ... ){    if ( level <= mEffectiveLevel )    {        char            classString[4];        char            timeString[64];        char            logString[8192];        va_list         argPtr;        struct timeval  timeVal;                if ( level < PANIC || level > DEBUG9 )            Panic( "Invalid logger level %d", level );        strncpy( classString, smCodes[level].c_str(), sizeof(classString) );        gettimeofday( &timeVal, NULL );    #if 0        if ( logRuntime )        {            static struct timeval logStart;            subtractTime( &timeVal, &logStart );            snprintf( timeString, sizeof(timeString), "%ld.%03ld", timeVal.tv_sec, timeVal.tv_usec/1000 );        }        else        {    #endif            char *timePtr = timeString;            timePtr += strftime( timePtr, sizeof(timeString), "%x %H:%M:%S", localtime(&timeVal.tv_sec) );            snprintf( timePtr, sizeof(timeString)-(timePtr-timeString), ".%06ld", timeVal.tv_usec );    #if 0        }    #endif        pid_t tid;#ifdef HAVE_SYSCALL        if ( (tid = syscall(SYS_gettid)) < 0 ) // Thread/Process id#endif // HAVE_SYSCALL        tid = getpid(); // Process id        char *logPtr = logString;        logPtr += snprintf( logPtr, sizeof(logString), "%s %s[%d].%s-%s/%d [",                     timeString,                    mId.c_str(),                    tid,                    classString,                    file,                    line                );        char *syslogStart = logPtr;        va_start( argPtr, fstring );        if ( hex )        {            unsigned char *data = va_arg( argPtr, unsigned char * );            int len = va_arg( argPtr, int );            int i;            logPtr += snprintf( logPtr, sizeof(logString)-(logPtr-logString), "%d:", len );            for ( i = 0; i < len; i++ )            {                logPtr += snprintf( logPtr, sizeof(logString)-(logPtr-logString), " %02x", data[i] );            }        }        else        {
开发者ID:369mario963,项目名称:ZoneMinder,代码行数:67,


示例20: main

int main(int argc, char *argv[]){		string server("129.194.32.96");	CalendarController::InputLang lang(CalendarController::INPUT_LANG_ENG);		if (argc >= 2)	{			string arg = argv[1];				if (arg == "ENG")		{			lang = CalendarController::INPUT_LANG_ENG;					}		else if (arg == "JAP")		{			lang = CalendarController::INPUT_LANG_JAP;				}		else		{			lang = CalendarController::INPUT_LANG_ENG;		}	}		if (argc == 3)	{			server = argv[2];	}	const struct tm* tm;	size_t len;	time_t now;	char* s;		now = time(NULL);	tm = localtime(&now);		s = new char[40];	len = strftime(s, 40, "%Y-%m-%d.%H-%M-%S", tm);	string str(s);	str = "../logs/test_calendar_gui." + str + ".output";		delete s;		ACE_OSTREAM_TYPE* output = 		new std::ofstream(str.c_str());	ACE_LOG_MSG->msg_ostream(output, 0);	ACE_LOG_MSG->set_flags(ACE_Log_Msg::OSTREAM);	ACE_LOG_MSG->set_flags(ACE_Log_Msg::VERBOSE_LITE);		ACE_LOG_MSG->priority_mask(LM_TRACE|LM_DEBUG, ACE_Log_Msg::PROCESS);		g_thread_init(NULL);	gdk_threads_init();	gdk_threads_enter();	gtk_init(&argc, &argv);	g_set_application_name(APP_NAME);		CalendarController calendarctl;	calendarctl.SetRemoteServersIP(server);	calendarctl.SetInputLang(lang);	calendarctl.RunApp();	ACE_LOG_MSG->clr_flags(ACE_Log_Msg::OSTREAM);	delete output;		gdk_threads_leave();		return 0;    }
开发者ID:carriercomm,项目名称:PrologMUD,代码行数:68,


示例21: main

intmain(int argc, char *argv[]){	fd_set              rfds, wfds;	struct cn_strct    *tp, *to;	int                 rnum, wnum, readsocks;	int                 i;	struct    tm       *tm_struct;	/* initialize the masterdate we update only every second */	_Last_loop = time(NULL);	tm_struct  = gmtime(&_Last_loop);	strftime( _Master_date, 32, "%a, %d %b %Y %H:%M:%S %Z", tm_struct);#if DEBUG_VERBOSE == 2	_Conn_count=0;#endif#if DEBUG_VERBOSE == 1	printf("STARTED AT: %s/n", _Master_date);#endif	signal(SIGQUIT, die);	signal(SIGTERM, die);	signal(SIGPIPE, check_sockets);	signal(SIGINT,  clean_on_quit);	/* Fill up the initial connection lists; _Free_conns is just a LIFO stack,	 * there shall never be a performance issues -> single linked only */	_Free_count=0;	for (i = 0; i < INITIAL_CONNS; i++) {		tp = _Free_conns;		_Free_conns = (struct cn_strct *) calloc(1, sizeof(struct cn_strct));		_Free_conns->data_buf_head =			(char *) calloc (RECV_BUFF_LENGTH, sizeof (char));		_Free_conns->c_next = tp;		_Free_conns->c_prev = NULL;		_Free_conns->q_prev = NULL;		_Free_conns->identifier = _Conn_count++;		_Free_count++;	}	/* create the master listener */	if ((_Master_sock = create_listener(HTTP_PORT)) == -1) {		fprintf(stderr, "ERR: Couldn't bind to port %d/n",				HTTP_PORT);		exit(1);	}	/* set up LIFO queue */	_Queue_tail = _Queue_head = NULL;	_Queue_count = 0;	/* create workers for application */	for(i = 0; i < WORKER_THREADS; i++) {		pthread_create(&_Workers[i], NULL, &run_app_thread, (void *) &i);	}	sleep(1);	for(i = 0; i < WORKER_THREADS; i++) {		pthread_detach( _Workers[i] );	}#if DEBUG_VERBOSE == 1	printf("%s: listening on port %d (http)/n",			_Server_version, HTTP_PORT);#endif	/* main loop */	while (1) {		// clean socket lists		FD_ZERO(&rfds);		FD_ZERO(&wfds);		wnum = -1;		// Add master listener to reading sockets		FD_SET(_Master_sock, &rfds);		rnum = _Master_sock;		// Add the established sockets		tp = _Busy_conns;		/* Adding connection to the SocketSets based on state */		while (tp != NULL) {			if (REQSTATE_READ_HEAD == tp->req_state) {				FD_SET(tp->net_socket, &rfds);				rnum = (tp->net_socket > rnum) ? tp->net_socket : rnum;			}			if (REQSTATE_SEND_FILE == tp->req_state) {				FD_SET(tp->net_socket, &wfds);				wnum = (tp->net_socket > wnum) ? tp->net_socket : wnum;			}			tp = tp->c_next;		}		readsocks = select(			(wnum > rnum) ? wnum+1 : rnum+1,			(-1 != rnum)  ? &rfds : NULL,			(-1 != wnum)  ? &wfds : NULL,			(fd_set *) 0,			NULL		);//.........这里部分代码省略.........
开发者ID:childhood,项目名称:parcle,代码行数:101,


示例22: main

main( void){char * host = "0.0.0.0";char * service = "2525";char * proto = "tcp";//char * proto = "sctp";struct sockaddr_in sin, remote;struct tm *tp;time_t t;int i, sd, rsd, rlen, readed, pid;char buf[513], t_str[512];    if ( (sd = mksock( host, service, proto, &sin)) == -1)    {		perror( "Ошибка при создании сокета");		return 1;    }    printf( "Адрес сервера %s = %s/n", host, (char *) (inet_ntoa( sin.sin_addr)));    printf( "Адрес порта сервера %s = %X/n", service, sin.sin_port);		i = 1;	i = setsockopt( sd, SOL_SOCKET, SO_REUSEADDR, &i, sizeof( &i));	if( i != 0) perror("Опция сокета (SOL_SOCKET, SO_REUSEADDR))");	if( bind( sd, (struct sockaddr *) &sin, sizeof( sin)) < 0)	{		perror( "Ошибка при привязке сокета");		return 1;	}	for ( i=0; i<CHILDS; i++)	{		pid = fork();		switch ( pid)		{			case -1:				perror( "Не создается дочерний процесс");				break;			case 0:				pid = i+1;				i=CHILDS+1;			break;			default:				pid=0;		}	}    if ( listen( sd, 0) == -1)    {	perror( "Ошибка при переводе сокета в пассивный режим");        return 1;	}    while(1)    {		rlen = sizeof( remote);		rsd = accept( sd, (struct sockaddr *)&remote, &rlen);		fprintf( stderr, "Process %d accepted connection/n", pid);		t = time( NULL);		tp = localtime( &t);		strftime( t_str, 512, "%a, %d %b %Y %T %z", tp);		snprintf( buf, 512, "Server [%d]: %s/n", pid, t_str );		send(rsd, buf, strlen(buf), 0);		close( rsd);    }    return 0;}
开发者ID:Baltazore,项目名称:spolks-lectures,代码行数:72,


示例23: find_hb

void find_hb (char * fname)   {     int       i, ii, j, jj, k ;        int       debug=0;    char buf1[20],buf2[20]; /* buffers for atomid routines */        char      calendar_s[128];        /* void find_ss()*/    /* {*/    /*     int i,j;*/    /*     float d;*/    time_t    calendar;    struct tm * calendar_tm_p;        char output_string[256]="/0";        /*     /* Check for disulphide bridges */	    if (!longoutflg)    { 	if (debug) printf("If !longoutflg/n"); 	 	time ( &calendar ); 	if (debug) printf("  time/n"); 	 	calendar_tm_p = localtime ( &calendar ); 	if (debug) printf("  calendar/n"); 	 	strftime(calendar_s,128,"%b %d %X %Z %Y/0",calendar_tm_p); 	if (debug) printf("  strftime/n"); 	 	fprintf(ofp,"HBPLUS Hydrogen Bond Calculator v %s            %s/n",VERSION,calendar_s ); 	fprintf(ofp,"(c) I McDonald, D Naylor, D Jones and J Thornton 1993 All Rights Reserved./n"); 	fprintf(ofp,"Citing HBPLUS in publications that use these results is condition of use./n"); 	fprintf(ofp,"%4.4s <- Brookhaven Code /"%s/" <- PDB file/n",brcode,fname); 	 	fprintf(ofp,"<---DONOR---> <-ACCEPTOR-->    atom                        ^               /n"); 	fprintf(ofp,"c    i                          cat <-CA-CA->   ^        H-A-AA   ^      H- /n"); 	fprintf(ofp,"h    n   atom  resd res      DA  || num        DHA   H-A  angle D-A-AA Bond/n"); 	fprintf(ofp,"n    s   type  num  typ     dist DA aas  dist angle  dist       angle   num/n"); 	/*	   <---DONOR---> <-ACCEPTOR-->    atom                        ^               	   c    i                          cat <-CA-CA->   ^        H-A-AA   ^      H- 	   h    n   atom  resd res      DA  ||   num      DHA   H-A  angle D-A-AA Bond	   n    s   type  num  typ     dist DA aas  dist angle  dist       angle   num	   E0010-LEU N   E0006-TYR O   3.07 MM   4  6.17 157.2  2.13 147.8 154.9    17	   */    }        /* First Pass : Check for disulphide bridges */            puts("Checking for hydrogen bonds . . . ");        for (ii = 0; ii < (natoms-1); ii++)    {	/* ignore atom incapable of H-bonding immediately */	if (atom[ii].aacode <TOTNAA &&	    donors[atom[ii].aacode][atom[ii].atmtyp] == 0 &&	    accepts[atom[ii].aacode][atom[ii].atmtyp] == 0)	    if (!nnbflg) 		continue;	for (jj = ii + 1; jj < natoms; jj++)	{ 	    debug=0; 	     	    if (atom[jj].aacode <TOTNAA &&		donors[atom[jj].aacode][atom[jj].atmtyp] == 0 &&		accepts[atom[jj].aacode][atom[jj].atmtyp] == 0)		if (!nnbflg) 		    continue;	     	    /* if the exchangeflg has been set to 2 by the -X option, only 	       do the hydrogen bonds for the His, Asn, and Gln side-chains */ 	    if (exchangeflg==2) 		if ( !( (atom[ii].atmtyp > 4 && (atom[ii].aacode == His 						 || atom[ii].aacode == Asn || atom[ii].aacode == Gln) ) 		       || ( atom[jj].atmtyp > 4 && (atom[jj].aacode == Asn  		    || atom[jj].aacode == Gln || atom[jj].aacode == His) ) 		       ) ) 		    continue; 	    	    /* ignore very distant atom pairs immediately */	    if (fabs(atom[ii].p.x - atom[jj].p.x) > HBDIST || 		fabs(atom[ii].p.y - atom[jj].p.y) > HBDIST || 		fabs(atom[ii].p.z - atom[jj].p.z) > HBDIST )	    {		if (debug == 2)		    printf("                      very distant, ignoring this pair!/n");		continue;	    }	    	    	    /* Check each IJ atom pair twice. I.e. check for I(don) / J(acc) 	       and J(don) / I(acc) */	    for (k = (nnbflg)?1:0; k < 2; k++) /* slightly opaque this one */ 		/* if nnbflg is set, then this loop only executes once, 		   because it doesn't matter which is the donor and which is//.........这里部分代码省略.........
开发者ID:mmravic314,项目名称:bin,代码行数:101,


示例24: main

//.........这里部分代码省略.........	tv.tv_usec = 100000;	FD_ZERO(&fds);	FD_SET(gpsdata.gps_fd, &fds);	errno = 0;	r = select(gpsdata.gps_fd+1, &fds, NULL, NULL, &tv);	if (r == -1 && errno != EINTR) {	    (void)fprintf(stderr, "gpspipe: select error %s(%d)/n",			  strerror(errno), errno);	    exit(EXIT_FAILURE);	} else if (r == 0)		continue;	if (vflag)	    spinner(vflag, l++);	/* reading directly from the socket avoids decode overhead */	errno = 0;	r = (int)read(gpsdata.gps_fd, buf, sizeof(buf));	if (r > 0) {	    int i = 0;	    int j = 0;	    for (i = 0; i < r; i++) {		char c = buf[i];		if (j < (int)(sizeof(serbuf) - 1)) {		    serbuf[j++] = buf[i];		}		if (new_line && timestamp) {		    char tmstr_u[20];            // time with "usec" resolution		    struct timeval now;		    struct tm *tmp_now;		    (void)gettimeofday( &now, NULL );		    tmp_now = localtime((time_t *)&(now.tv_sec));		    (void)strftime(tmstr, sizeof(tmstr), format, tmp_now);		    new_line = 0;		    switch( option_u ) {		    case 2:			(void)snprintf(tmstr_u, sizeof(tmstr_u), 				       " %ld.%06ld", now.tv_sec, now.tv_usec);			break;		    case 1:			(void)snprintf(tmstr_u, sizeof(tmstr_u), 				       ".%06ld", now.tv_usec);			break;		    default:			*tmstr_u = '/0';			break;		    }		    if (fprintf(fp, "%.24s%s: ", tmstr, tmstr_u) <= 0) {			(void)fprintf(stderr,				      "gpspipe: write error, %s(%d)/n",				      strerror(errno), errno);			exit(EXIT_FAILURE);		    }		}		if (fputc(c, fp) == EOF) {		    fprintf(stderr, "gpspipe: Write Error, %s(%d)/n",			    strerror(errno), errno);		    exit(EXIT_FAILURE);		}		if (c == '/n') {		    if (serialport != NULL) {			if (write(fd_out, serbuf, (size_t) j) == -1) {
开发者ID:idaohang,项目名称:gpsd-2,代码行数:67,


示例25: onion_shortcut_date_string_iso

/** * @short Transforms a time_t to a ISO date string *  * The dest pointer must be at least 21 bytes long as thats the maximum size of the date. */void onion_shortcut_date_string_iso(time_t t, char *dest){	struct tm ts;	gmtime_r(&t, &ts);	strftime(dest, t, "%FT%TZ", &ts);}
开发者ID:cemonds,项目名称:onion,代码行数:10,


示例26: test_merge_conflicts

//.........这里部分代码省略.........    /* modify/modify conflict. */    fp_a = g_fopen (file_a, "w+b");    if (!fp_a) {        fprintf (stderr, "Failed to open %s: %s/n", file_a, strerror(errno));        return -1;    }    fprintf (fp_a, "abcabc/nabcabc");    fclose (fp_a);    /* df conflict occurs only when files are changed. */    fp_b = g_fopen (file_b, "wb");    if (!fp_b) {        fprintf (stderr, "Failed to open %s: %s/n", file_b, strerror(errno));        return -1;    }    fprintf (fp_b, "12345678");    fclose (fp_b);        /* modify/delete conflict. */    g_unlink (file_c);    /* df conflict occurs only when files are changed. */    snprintf (cmd, 1024, "cp %s %s", file_e, file_f);    ret = system (cmd);    if (ret < 0 || WEXITSTATUS(ret) != 0) {        fprintf (stderr, "Failed to cp %s to %s/n", file_e, file_f);        return -1;    }    sleep (2);    if (seaf_repo_index_add (repo, "") < 0) {        fprintf (stderr, "Failed to add on branch test/n");        return -1;    }    printf ("*** creating new commit on branch test./n");    remote = seaf_repo_index_commit (repo, "merge test 2.", FALSE, NULL, &error);    if (!remote) {        fprintf (stderr, "Failed to commit on branch test/n");        return -1;    }    printf ("*** checking out branch local./n");    /* switch back to branch "local". */    if (seafile_checkout (repo->id, "local", &error) < 0) {        fprintf (stderr, "Failed to checkout branch local/n");        fprintf (stderr, "Checkout error messages:/n%s", error->message);        return -1;    }    sleep (2);    printf ("*** merging test to local./n");    /* merge branch "test". */    if (seafile_merge (repo->id, "test", &error) == 0) {        fprintf (stderr, "This merge is supposed to fail!!/n");        return -1;    }    fprintf (stderr, "Merge error messages:/n%s", error->message);    printf ("*** check merge conflict results./n");    if (g_access (file_f, F_OK) != 0) {        fprintf (stderr, "Bug: %s should exist./n", file_a);        return -1;    }    if (g_access (file_c, F_OK) != 0) {        fprintf (stderr, "Bug: %s should exist./n", file_c);        return -1;    }	time_t t = time(NULL);	strftime(buf, 64, "--plt_%Y-%m-%d", localtime(&t));    char *file_a_local = g_strconcat (file_a, buf, NULL);    char *file_a_test = g_strconcat (file_a, "", NULL);    if (check_file_content (file_a_local, "xyzxyz/nxyzxyz", 13) < 0)        return -1;    if (check_file_content (file_a_test, "abcabc/nabcabc", 13) < 0)        return -1;    char *file_d_local = g_strconcat (file_d, buf, NULL);    if (check_file_content (file_d_local, "1234/n1234/n", 10) < 0)        return -1;    if (check_dir (file_d) < 0) {        return -1;    }    char *dir_b_test = g_strconcat (file_b, buf, NULL);    if (check_file_content (file_b, "12345678", 8) < 0)        return -1;    if (check_dir (dir_b_test) < 0) {        return -1;    }    printf ("/n=== Successfully handle merge conflict./n/n");    return 0;}
开发者ID:90songjian,项目名称:seafile,代码行数:101,


示例27: lws_http_action

//.........这里部分代码省略.........#ifdef LWS_WITH_ACCESS_LOG	/*	 * Produce Apache-compatible log string for wsi, like this:	 *	 * 2.31.234.19 - - [27/Mar/2016:03:22:44 +0800]	 * "GET /aep-screen.png HTTP/1.1"	 * 200 152987 "https://libwebsockets.org/index.html"	 * "Mozilla/5.0 (Macint... Chrome/49.0.2623.87 Safari/537.36"	 *	 */	{		static const char * const hver[] = {			"http/1.0", "http/1.1", "http/2"		};#ifdef LWS_USE_IPV6		char ads[INET6_ADDRSTRLEN];#else		char ads[INET_ADDRSTRLEN];#endif		char da[64];		const char *pa, *me;		struct tm *tmp;		time_t t = time(NULL);		int l = 256;		if (wsi->access_log_pending)			lws_access_log(wsi);		wsi->access_log.header_log = lws_malloc(l);		tmp = localtime(&t);		if (tmp)			strftime(da, sizeof(da), "%d/%b/%Y:%H:%M:%S %z", tmp);		else			strcpy(da, "01/Jan/1970:00:00:00 +0000");		pa = lws_get_peer_simple(wsi, ads, sizeof(ads));		if (!pa)			pa = "(unknown)";		if (meth >= 0)			me = method_names[meth];		else			me = "unknown";		snprintf(wsi->access_log.header_log, l,			 "%s - - [%s] /"%s %s %s/"",			 pa, da, me, uri_ptr,			 hver[wsi->u.http.request_version]);		l = lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_USER_AGENT);		if (l) {			wsi->access_log.user_agent = lws_malloc(l + 2);			lws_hdr_copy(wsi, wsi->access_log.user_agent,				     l + 1, WSI_TOKEN_HTTP_USER_AGENT);		}		wsi->access_log_pending = 1;	}#endif	/* can we serve it from the mount list? */	hm = wsi->vhost->mount_list;	while (hm) {		if (uri_len >= hm->mountpoint_len &&
开发者ID:Fooway,项目名称:libwebsockets,代码行数:67,


示例28: listBucketCallback

S3Status listBucketCallback(int isTruncated, const char *nextMarker,                                   int contentsCount,                                   const S3ListBucketContent *contents,                                   int commonPrefixesCount,                                   const char **commonPrefixes,                                   void *callbackData){    list_bucket_callback_data *data =        (list_bucket_callback_data *) callbackData;    data->isTruncated = isTruncated;    // This is tricky.  S3 doesn't return the NextMarker if there is no    // delimiter.  Why, I don't know, since it's still useful for paging    // through results.  We want NextMarker to be the last content in the    // list, so set it to that if necessary.    if ((!nextMarker || !nextMarker[0]) && contentsCount) {        nextMarker = contents[contentsCount - 1].key;    }    if (nextMarker) {        snprintf(data->nextMarker, sizeof(data->nextMarker), "%s",                 nextMarker);    }    else {        data->nextMarker[0] = 0;    }//    if (contentsCount && !data->keyCount) {//        printListBucketHeader(data->allDetails);//    }    int i;    for (i = 0; i < contentsCount; i++) {        const S3ListBucketContent *content = &(contents[i]);        char timebuf[256];        time_t t = (time_t) content->lastModified;        strftime(timebuf, sizeof(timebuf), "%Y-%m-%dT%H:%M:%SZ",                 gmtime(&t));        char sizebuf[16];        if (content->size < 100000) {            sprintf(sizebuf, "%5llu", (unsigned long long) content->size);        }        else if (content->size < (1024 * 1024)) {            sprintf(sizebuf, "%4lluK",                    ((unsigned long long) content->size) / 1024ULL);        }        else if (content->size < (10 * 1024 * 1024)) {            float f = content->size;            f /= (1024 * 1024);            sprintf(sizebuf, "%1.2fM", f);        }        else if (content->size < (1024 * 1024 * 1024)) {            sprintf(sizebuf, "%4lluM",                    ((unsigned long long) content->size) /                    (1024ULL * 1024ULL));        }        else {            float f = (content->size / 1024);            f /= (1024 * 1024);            sprintf(sizebuf, "%1.2fG", f);        }        savedContents.append(*content);        savedKeys.append(content->key);    }    data->keyCount += contentsCount;    for (i = 0; i < commonPrefixesCount; i++) {        savedCommonPrefixes.append(commonPrefixes[i]);    }    return S3StatusOK;}
开发者ID:ephemerr,项目名称:s3bar,代码行数:72,


示例29: escuchaCliente

int escuchaCliente(int socket, struct sockaddr_in addr){    char buffer[BUFFERSIZE];    char aux[BUFFERSIZE];    int bytecount;    int fin=0;    int code=0;         /* Código de salida por defecto */    time_t t;    struct tm *tmp;    socklen_t slen=sizeof(addr);    while (!fin)      {    memset(buffer, 0, BUFFERSIZE);       if((bytecount=recvfrom(socket,buffer,BUFFERSIZE,0,(struct sockaddr*)&addr,&slen))==-1)       {       error(5, "No puedo recibir información");         }printf("%s/n",buffer);    /* Evaluamos los comandos */    /* El sistema de gestión de comandos es muy rudimentario, pero nos vale */    /* Comando TIME - Da la hora */    if (strncmp(buffer, "TIME", 4)==0)      {        memset(buffer, 0, BUFFERSIZE);        t = time(NULL);        tmp = localtime(&t);        strftime(buffer, BUFFERSIZE, "%Y-%m-%d %H:%M:%S", tmp);      }        /* Comando EXIT - Cierra la conexión actual */    else if (strncmp(buffer, "EXIT", 4)==0)      {        memset(buffer, 0, BUFFERSIZE);        sprintf(buffer, "Hasta luego. Vuelve pronto %s/n", inet_ntoa(addr.sin_addr));        fin=1;      }    /* Comando CERRAR - Cierra el servidor */    else if (strncmp(buffer, "CERRAR", 6)==0)      {        memset(buffer, 0, BUFFERSIZE);        sprintf(buffer, "Adiós. Cierro el servidor/n");        fin=1;        code=99;        /* Salir del programa */      }    else      {             sprintf(aux, "ECHO: %s/n", buffer);        strcpy(buffer, aux);      }     if(bytecount = sendto(socket,buffer,strlen(buffer),0, (struct sockaddr*)&addr, sizeof(addr))==-1){          error(6, "No puedo enviar información");     }}     close(socket);    return code;}
开发者ID:Cesarhh15,项目名称:Sistemas-Distribuidos,代码行数:63,


示例30: win32_strftime_extra

static apr_size_t win32_strftime_extra(char *s, size_t max, const char *format,                                       const struct tm *tm) {   /* If the new format string is bigger than max, the result string won't fit    * anyway. If format strings are added, made sure the padding below is    * enough */    char *new_format = (char *) malloc(max + 11);    size_t i, j, format_length = strlen(format);    apr_size_t return_value;    int length_written;    for (i = 0, j = 0; (i < format_length && j < max);) {        if (format[i] != '%') {            new_format[j++] = format[i++];            continue;        }        switch (format[i+1]) {            case 'C':                length_written = apr_snprintf(new_format + j, max - j, "%2d",                    (tm->tm_year + 1970)/100);                j = (length_written == -1) ? max : (j + length_written);                i += 2;                break;            case 'D':                /* Is this locale dependent? Shouldn't be...                   Also note the year 2000 exposure here */                memcpy(new_format + j, "%m/%d/%y", 8);                i += 2;                j += 8;                break;            case 'r':                memcpy(new_format + j, "%I:%M:%S %p", 11);                i += 2;                j += 11;                break;            case 'R':                memcpy(new_format + j, "%H:%M", 5);                i += 2;                j += 5;                break;            case 'T':                memcpy(new_format + j, "%H:%M:%S", 8);                i += 2;                j += 8;                break;            case 'e':                length_written = apr_snprintf(new_format + j, max - j, "%2d",                    tm->tm_mday);                j = (length_written == -1) ? max : (j + length_written);                i += 2;                break;            default:                /* We know we can advance two characters forward here. Also                 * makes sure that %% is preserved. */                new_format[j++] = format[i++];                new_format[j++] = format[i++];        }    }    if (j >= max) {        *s = '/0';  /* Defensive programming, okay since output is undefined*/        return_value = 0;    } else {        new_format[j] = '/0';        return_value = strftime(s, max, new_format, tm);    }    free(new_format);    return return_value;}
开发者ID:Ga-vin,项目名称:apache,代码行数:68,



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


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