whoami实现
#include<stdio.h>#include<pwd.h>#include<sys/types.h>#include<unistd.h>int main(){ uid_t id; struct passwd * pa; id=geteuid(); pa=getpwuid(id); printf("%d\n",id); printf("%s\n",pa->pw_name);
return 0;}cp实现
cp实现
/#define S_ISDIR(x) (((x)&STAT_MASK)==STAT_DIR_FLAG)STAT_MASK 001000001010STAT_DIR_FLAG 001000000000/#include<stdio.h>#include<unistd.h> //close#include<fcntl.h> //open#include <sys/stat.h>#include <string.h> #include<utime.h>//use to change time//int utime(const char filename,struct utimbuf buf); #define BUFSIZE 4096#define COPYMODE 0644 //文件许可位 permission bit void oops(char * sl,char * s2) { fprintf(stderr,"Error: %s ",sl); perror(s2); //传来一个文件地址,然后让它判断错误原因。 exit(1);}main(int ac,char av[]){ int in_fd,out_fd,n_chars; char buf[BUFSIZE]; struct stat st; struct utimbuf utbuf; if(ac!=3) { fprintf(stderr,“usage: %s source destination\n”,av); printf(“your parameters are not enough\n”); exit(1); } if( (in_fd=open(av[1],O_RDONLY)) == -1 ) { oops("Cannot open ",av[1]); } if( (out_fd=creat(av[2],COPYMODE)) == -1 ) { //实现了输入目录也可以复制。 但是字符串的截取复杂************ if(stat(av[2],&st)!=-1) { if(S_ISDIR(st.st_mode)) { char tp[100]; int i,j=0; for(i=strlen(av[1])-1;i>=0;i–) { if(av[1][i]’/’)break; } for(i++;i<strlen(av[1]);i++) { tp[j++]=av[1][i]; } tp[j]=’\0’; //strncpy(av[2]+strlen(av[2]),"/\0",2); //strcpy(av[2]+strlen(av[2]),av[1] ); strcpy(av[2]+strlen(av[2]),tp); strncpy(av[2]+strlen(av[2]),"\0",1); if( (out_fd=creat(av[2],COPYMODE)) == -1 ) { oops("Cannot creat ",av[2]); } } } else oops("Cannot creat ",av[2]); } if(stat(av[1],&st)-1) { oops("Cannot read ",av[1]); } while( (n_chars = read(in_fd,buf,BUFSIZE))>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]); } if((close(out_fd) == -1) | (close(in_fd)== -1)) { oops(“Error closing files “,””); } utbuf.actime=st.st_atime; utbuf.modtime=st.st_mtime; if(-1==utime(av[2],&utbuf)) { oops(“Error changing time “,””); } printf(“Copy has finished,you can use ‘ls’ to see it\n”); }/*st_atime 文件数据的最后存取时间 read -u st_mtime 文件数据的最后修改时间 write 缺省 st_ctime 文件属性的最后更改时间 chown,chmod -c