time函数及相关
1 #include <cstdlib> 2 #include <iostream> 3 #include <ctime> 4 5 using namespace std; 6 7 int main( int argc, char *argv[]); 8 void timestamp( void); 9 10 int main( int argc, char *argv[]) 11 // argv : a pointer ( point to an array ( array stores pointers)) 12 { 13 int i; 14 bool VERBOSE = true; 15 16 if( VERBOSE) 17 { 18 timestamp(); 19 20 cout << "\n"; 21 cout << "ARGS\n"; 22 cout << " C++ version\n"; 23 cout <<"\n"; 24 cout << " Compiled on " << __DATE__ << "at" << __TIME__ << ".\n"; //显示编译时的时间 25 cout << __FILE__ <<endl; 26 cout << "\n"; 27 cout << " Print the commond line arguments of a C++ program.\n"; 28 cout << "\n"; 29 cout << " ARGC reports the number of arguments as " << argc << ".\n"; 30 cout << "\n"; 31 } 32 33 for( i = 0; i < argc; ++i) 34 { 35 cout << i << " " << *argv << "\n"; 36 argv++; 37 } 38 39 if( VERBOSE) 40 { 41 cout << "\n"; 42 cout << "ARGS:\n"; 43 cout << "Normal end of execution.\n"; 44 cout << "\n"; 45 timestamp(); 46 } 47 48 return 0; 49 50 } 51 52 void timestamp( void) 53 { 54 #define TIME_SIZE 40 // tips : 局部的宏定义 55 static char time_buffer[TIME_SIZE]; 56 const struct tm *tm; // time 的结构体,包含时间的信息。 57 size_t len; 58 time_t now; //就是int64变量 59 60 now = time( NULL); // 形成时间的信息,存储在now中 61 tm = localtime( &now); // 将now中的信息转换到tm中 62 len = strftime( time_buffer, TIME_SIZE, "%d %B %Y %I:%M:%S %p", tm); // 将tm中的信息转到time_buffer中, 63 cout << time_buffer << "\n"; // 在字符串中显示。 64 return ; 65 # undef TIME_SIZE 66 }
学习到的东西:编译器预定义到的宏。http://blog.csdn.net/the__blue__sky/article/details/8921488 http://blog.csdn.net/q191201771/article/details/6092891
再次理解main函数的参数“ char *argv[]",argv[]是个数组,数组里面存储的是char* 指针,即数组里面的内容是指针。
// wchar.h 中 struct tm { int tm_sec; /* seconds after the minute - [0,59] */ int tm_min; /* minutes after the hour - [0,59] */ int tm_hour; /* hours since midnight - [0,23] */ int tm_mday; /* day of the month - [1,31] */ int tm_mon; /* months since January - [0,11] */ int tm_year; /* years since 1900 */ int tm_wday; /* days since Sunday - [0,6] */ int tm_yday; /* days since January 1 - [0,365] */ int tm_isdst; /* daylight savings time flag */ };
time()获得时间信息;localtime()转换信息为时间表示的形式;strftime()将时间转换为字符串的形式,便于输出。
原型:time_t time( time_t* timer) The value returned generally represents the number of seconds since 00:00 hours, Jan 1, 1970 UTC. 将返回的值返回到timer里面。如果timer是NULL 则返回就完了。
源代码来源:http://people.sc.fsu.edu/~jburkardt/cpp_src/args/args.cpp