常用的Linux C函数介绍

终端控制与环境变量设置函数

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指针所指的内存。 
2.ctime()将时间和日期以字符串格式形式表示:
函数原型: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);
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值