所以我正在使用linux,我的问题是如何使程序接受执行中的参数,如下所示:
./ program am i
目前这两个函数的工作方式相同,因为我只是在努力获取这一行: (show_info_who_am_i的预期结果)
Kamil pts / 0 2015-11-12 10:14(:0)
而不是两者: (show_info_who的结果)
Kamil tty2 2015-11-12 10:13(:0)
Kamil pts / 0 2015-11-12 10:14(:0)
#include <stdio.h>
#include <utmp.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
#include <sys/types.h>
#define SHOWHOST /* include remote machine on output */
show_info_who( struct utmp *utbufp )
{
if(utbufp->ut_type > 4){
time_t czas = utbufp->ut_time;
char buf[80];
struct tm* timeinfo = localtime(&czas);
printf("%-8.8s", utbufp->ut_name); /* the logname */
printf(" "); /* a space */
printf("%-8.8s", utbufp->ut_line); /* the tty */
printf(" "); /* a space */
strftime(buf, 80, "%F %R" , timeinfo);
printf("%s", buf);
printf(" "); /* a space */
#ifdef SHOWHOST
printf("(%s)", utbufp->ut_host); /* the host */
#endif
printf("\n"); /* newline */
}
}
show_info_who_am_i( struct utmp *utbufp )
{
if(utbufp->ut_type > 4){
time_t czas = utbufp->ut_time;
char buf[80];
struct tm* timeinfo = localtime(&czas);
printf("%-8.8s", utbufp->ut_name); /* the logname */
printf(" "); /* a space */
printf("%-8.8s", utbufp->ut_line); /* the tty */
printf(" "); /* a space */
strftime(buf, 80, "%F %R" , timeinfo);
printf("%s", buf);
printf(" "); /* a space */
#ifdef SHOWHOST
printf("(%s)", utbufp->ut_host); /* the host */
#endif
printf("\n"); /* newline */
}
}
int main(int argc, char *argv[])
{
struct utmp current_record; /* read info into here */
int utmpfd; /* read from this descriptor */
int reclen = sizeof(current_record);
if ( (utmpfd = open(UTMP_FILE, O_RDONLY)) == -1 ){
perror( UTMP_FILE ); /* UTMP_FILE is in utmp.h */
exit(1);
}
//char am[22] = "am"; /* test */
//char i[22] = "i"; /* test */
//printf("%s,%s\n\n", am,i); /* test */
//printf("%s", argv[1]);
if(argv[1]== "am"){
if(argv[2]== "i"){
while ( read(utmpfd, ¤t_record, reclen) == reclen )
show_info_who_am_i(¤t_record);
}
}
else{
while ( read(utmpfd, ¤t_record, reclen) == reclen )
show_info_who(¤t_record);
}
//printf("%s,%s", argv[1], argv[2]); /* test */
close(utmpfd);
return 0; /* went ok */
}