在阅读unix/linux编程实践教程时阅读到第二章有个疑问,参看如下代码
#include <stdio.h>
#include <stdlib.h>
#include <utmp.h>
#include <fcntl.h>
#include <unistd.h>
#include <time.h>
void showtime( long );
void show_info( struct utmp * utbufp );
int main()
{
struct utmp current_record;
int utmpfd;
int reclen = sizeof( current_record );
if ( ( utmpfd = open( UTMP_FILE, O_RDONLY ) ) == -1 ){
perror( UTMP_FILE );
exit( 1 );
}
while ( read( utmpfd, ¤t_record, reclen ) == reclen )
show_info( ¤t_record );
close( utmpfd );
return 0;
}
void show_info( struct utmp *utbufp )
{
if ( utbufp->ut_type != USER_PROCESS )
return;
printf("%-8.8s ", utbufp->ut_name );
printf("%-8.8s ", utbufp->ut_line );
showtime( utbufp->ut_time );
#ifdef SHOWHOST
if ( utbufp->ut_host[ 0 ] != '\0' )
printf("(%s)", utbufp->ut_host);
#endif
printf("\n");
}
void showtime( long timeval )
{
char *cp;
cp = ctime( &timeval );
printf("%12.12s", cp + 4 );
}
前面一些介绍就不管了,在show_info函数中打印了ut_name结构成员,可是我找到该结构体定义的地方发现该结构没有这个成员,这就很奇怪了。
可是我去掉ut_name,确又不显示登录的用户名了,现在只能怀疑我找的定义的地方不对,我找到的地方是:
vi /usr/include/x86_64-linux-gnu/bits/utmp.h
另外关于printf中 -8.8s存在疑问,一般格式控制中-8.8s,左对齐,小数点前8位,小数点之后8位,可是printf对应的却是字符串,这该如何解释?
ut_user
应该起的就是ut_name
的作用, 你找下, 应该文件顶部#define ut_name ut_user
过了小数点前面的数限定了整个打印长度多长, 小数点后面的数限定了能显示的字符串的最大长度:
output:
虽然没有在标准里面找, 但是我开了-pedantic-errors, 所以这的确是标准里面规定而不是编译器的扩展, 所以字符串是能这样格式化输出的