who命令实现

在阅读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, &current_record, reclen ) == reclen )
        show_info( &current_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对应的却是字符串,这该如何解释?

阅读 3.1k
1 个回答
可是我找到该结构体定义的地方发现该结构没有这个成员,这就很奇怪了。

ut_user应该起的就是ut_name的作用, 你找下, 应该文件顶部#define ut_name ut_user过了

另外关于printf中 -8.8s存在疑问,一般格式控制中-8.8s,左对齐,小数点前8位,小数点之后8位,可是printf对应的却是字符串,这该如何解释?

小数点前面的数限定了整个打印长度多长, 小数点后面的数限定了能显示的字符串的最大长度:

#include <stdio.h>
int main()
{
    char str[] = "abcdefghij";
    printf("Here are 10 chars: %8.4s\n", str);
    printf("Here are 10 chars: %4.8s\n", str);
    printf("Here are 10 chars: %-8.4s\n", str);
    printf("Here are 10 chars: %-4.8s\n", str);
    return 0;
}   
 clang prog.c -Wall -Wextra -std=c89 -pedantic-errors 

output:

Here are 10 chars: abcd
Here are 10 chars: abcdefgh
Here are 10 chars: abcd
Here are 10 chars: abcdefgh

虽然没有在标准里面找, 但是我开了-pedantic-errors, 所以这的确是标准里面规定而不是编译器的扩展, 所以字符串是能这样格式化输出的

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题