1. 程式人生 > >linux whoami cp mv mesg 命令 c語言實現

linux whoami cp mv mesg 命令 c語言實現

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