1. 程式人生 > >Linux環境-環境變數、時間和日期

Linux環境-環境變數、時間和日期

環境變數

環境由一組格式為“名字=值“的字串組成

在C語言程式中可以通過putenv和getenv函式來訪問和設定環境變數,

在environ變數中儲存有程式的所有環境變數,它以null結尾。

#include <stdlib.h>

extern char **environ;

char *getenv(const char *name);

name: 為環境變數的名稱 例如HOME

返回值 若環境變數有相關值則返回相關值,若無相關值則返回值的第一個位元組時null

            若不存在查詢的環境變數則返回null

int putenv( const char *string);

string 為 ”名字=值“的字串作為引數,並將該字串加到當前環境中。

返回值:如果由於記憶體不足導致不能擴充套件環境,他會返回  -1,並設定錯誤變數errno為ENOMEM

通過如下形式也可以為程式設定環境變數

$ FRED=hello ./env FRED

Variable FRED has value hello

時間和日期

所有的UNIX系統都是以格林尼治時間1970年1月1日0點開始計時的。從那時開始以秒計時。
用一個time_t來存放時間,其實是一個long ing型
#include <time.h>

time_t time(time_t *tloc);

獲取時間,返回值和,tloc都可以獲得時間

double difftime(time_t time1, time_t time2); //為了最大限度的考慮可移植性,最好使用此函式

獲得兩個時間的時間差,並將time1-time2的值作為浮點數返回

struct tm *gmtime(const time_t *timeval); //get man time ?將time獲得的時間轉換為年月日時分秒(獲得的時間為零時區時間)

stuct tm *localtime(const time_t *timeval)獲得的時間為本時區時間

timeval: time函式獲得的時間值

tm結構體:

int tm_sec 秒 0~61 //閏秒或雙閏秒

int tm_min 分 0~59

int tm_hour 時

int tm_mday 日

int tm_mon 月

int tm_year 年

int tm_wday 星期幾

int tm_yday 一年中的第幾天,0~366

int tm_isdst 是否夏令時

time_t mktime (struct tm *timeptr);//將strut tm 轉換為 time_t 如果struct tm不能被轉換返回-1

char *asctime(const struct tm *timeptr);//將給定的tm結構時間按照固定的字串格式輸出

char *ctime(const time_t *timeval);//以原始時間值為引數,並將它轉換為一個更易讀的本地時間。相當於asctime(localtime(timeval));

size_t strftime(char *s, size_t maxsize, const char *format, struct tm *timeptr);//格式化輸出tm結構中的時間(string format time = strftime)

例如:年月日時分秒 “%Y%m%d%H%M%S“

char *strptime(const char *buf, const char *format, struct tm *timeptr);//讀取字串buf中的日期到timeptr中,返回char指標指向buf中不能識別的字元