终端控制与环境变量设置函数
1,getopt()分析命令行参数:
需要头文件:#include<unistd.h>
函数原型:int getopt(int argc,char*const argv[],const char*opstring);
函数的返回值:如果找到符合的函数,则返回次参数字母,如果参数不包含在参数opt-sting的选项字母,则返回“?”字符,分析结束则返回-1.
函数说明:getopt()用来分析命令行参数。参数argc和argv是由main()传递的参数个数和内容。参数opsting则代表预处理的选项字符串。此函数会返回在argy中的下一个选项字母,此字母会对应参数opsting中的字母。
#include<stdio.h>
#include<unistd.h>
int main (int argc,char**argv)
{
int ch;
opterr=0;
while((ch=getopt(argc,argv,"a:bcde"))!=-1)
switch(ch)
{
case'a':printf("option a:'%s'\n",optarg);
break;
case'b':printf("option b:b\n");
break;
default:printf("other option:%c\n",ch);
}
printf("optopt+%c\n",optopt);
}
结果输出:
a.out -all
option a:'11'
optopt +
2.ttyname()返回一终端机名称
需要头文件:#include<unistd.h> | |
函数原型:char*ttyname(int desc) | |
函数返回值:如果成功则返回指向终端机名称的字符串指针,有错误情况发生时,则返回NULL。如果参数desc所代表的文件描述词为一终端机,则会将此终端机名称由一字符差串指针返回,否则返回NULL. |
ttyname返回终端机名称:
#include<stadio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
main()
{
int fd;
char * file="/dev/tty";
fd=open(file,O_RDONLY);
printf("%s",file);
if(isatty(fd))
{
printf("is a tty.\n");
printf(" ttyname=%s \n",ttyname(fd));
}
else printf("is not a tty\n");
close(fd);
}
输出结果:
/dev/ttyis a tty.
ttyname=/dey/tty
日期时间函数
1,time()取得目前的时间:
函数原型:time_t time(time_t *t); | |
函数返回值:成功则返回秒数,失败则返回(-1)值。 | |
函数说明:此函数会返回公元1970年1月1日的UTC时间从0时0分0秒起到现在所经过的秒数。如果t为空指针的话,此函数也会将返回值存到t指针所指的内存。 |
函数原型:char*ctime(const time_t*timep); | |
函数说明:ctime()将参数timep所指的time_t结构中的信息转换成真实世界所使用的时间日期表示方法,然后将结果以字符串形式返回。 | |
函数返回值:返回一个字符串表示目前当地的时间日期。这个字符串的长度只固定的为26.例如Thu Dec 7 14:58:59 2000 |
#include<stdio.h>
#include<time.h>
main()
{
time_t timep;
time (&timep);
printf(“%s”,ctime(&timep));
}
输出结果:
Sat Oct 28 10 : 12 : 05 2000
gmtime()取得目前的时间和日期。
头文件:#include <time.h> | |
定义函数:struct tm *gmtime(const time_t *timep); | |
函数说明:gmtime()将参数timep 所指的time_t 结构中的信息转换成真实世界所使用的时间日期表示方法,然后将结果由结构tm 返回。 |
#include <time.h>
main(){
char *wday[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
time_t timep;
struct tm *p;
time(&timep);
p = gmtime(&timep);
printf("%d%d%d", (1900+p->tm_year), (1+p->tm_mon), p->tm_mday);
printf("%s%d;%d;%d\n", wday[p->tm_wday], p->tm_hour, p->tm_min, p->tm_sec);
}