cp和who

来源:互联网 发布:小三转正后的婚姻知乎 编辑:程序博客网 时间:2024/05/01 05:47

 

#include        <stdio.h>
#include        <stdlib.h>
#include        <unistd.h>
#include        <fcntl.h>
#define BUFFERSIZE      4096
#define COPYMODE        0644
int oops(char *, char *);
main(int ac, char *av[])
{
        int     in_fd, out_fd, n_chars;
        char    buf[BUFFERSIZE];
      /* check args  */
        if ( ac != 3 ){
                fprintf( stderr, "usage: %s source destination/n", *av);
                exit(1);
        }
      /* open files */
        if ( (in_fd=open(av[1], O_RDONLY)) == -1 )
                oops("Cannot open ", av[1]);
        if ( (out_fd=creat( av[2], COPYMODE)) == -1 )
                oops( "Cannot creat", av[2]);
 
      /* copy files */
        while ( (n_chars = read(in_fd , buf, BUFFERSIZE)) > 0 )
                if ( write( out_fd, buf, n_chars ) != n_chars )
                        oops("Write error to ", av[2]);
 if ( n_chars == -1 )
   oops("Read error from ", av[1]);
      /* close files */
        if ( close(in_fd) == -1 || close(out_fd) == -1 )
                oops("Error closing files","");
}
int oops(char *s1, char *s2)
{
        fprintf(stderr,"Error: %s ", s1);
        perror(s2);
        exit(1);
}
linux下who命令的实现方式:
下面介绍一下如何编写这样的程序,通过查看who的命令文档可以查看到登陆用的信息被记录了/var/run/utmp,/var/log/wtmp文件中,关于相关的结构可以在/usr/include/utmp.h下查看,在该文件中包含了一个头文件#include <bits/utmp.h>,这个文件中有具体的utmp结构:
#include<stdio.h>
#include<utmp.h>
#include<unistd.h>
#include<fcntl.h>
#include<time.h>
 
void Timeformat(long timearg)
{
    char *p;    /*声明一个指针变量,在后面用来存放时间的地址*/
    p=ctime(&timearg); /*格式化时间*/
    printf("%12.12s/n", p+4); /*ctime返回的字符串从第四个字符开始*/
}
/*以上为格式化输出时间*/
void Showmessage(struct utmp * utmparg)
{
  
   if(utmparg->ut_type != USER_PROCESS)/*判断登陆类型时候是“用户”*/
   return;
   printf("%-8.8s", utmparg->ut_name ); /*输出登陆的用户名*/
   printf(" ");
   printf("%-8.8s",utmparg->ut_line); /*输出登陆的TTY*/
   printf(" ");
   Timeformat(utmparg->ut_time); /*输出登陆的时间*/
 
}
 
/*以上为输出当我们输入who命令后输出的信息*/
int main()
{
    struct utmp pointer;   /*声明utmp结构变量*/
    int utmpfd; /*打开的utmp文件存放在这里*/
    int re=sizeof(pointer);
   
    if((utmpfd = open(UTMP_FILE, O_RDONLY)) == 1){/*打开utmp文件,前面说过UTMP_FILE文件在paths.h中有定义*/
    printf("error/n");
    exit(1);
    }
 
    while( read(utmpfd, &pointer, re) == re)/*读取文件中的内容*/
    Showmessage(&pointer); /*调用Showmessage函数*/
    close(utmpfd); /*关闭utmp文件*/
    return 0;

  

原创粉丝点击