- mycp.c的功能與系統cp程序相同
- 將源文件復制到目標文件,例子如下:
- 要求使用系統調用open/read/write/close實現
$ cat /etc/passwd
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
bin:x:2:2:bin:/bin:/usr/sbin/nologin
...
$ ./mycp /etc/passwd passwd.bak
$ cat passwd.bak
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
bin:x:2:2:bin:/bin:/usr/sbin/nologin
實現思路:從main
中接受mycp
的參數,open
源文件,用stat
獲取文件大小,read
源文件,open
目標文件,將從源文件中讀取的字符寫入目標文件中。
實現代碼
#include<stdio.h>
#include<stdlib.h>#include<sys/types.h>
#include<unistd.h>#include<sys/stat.h>
#include<fcntl.h>int main(int argc,char *argv[]){int fd;int fsize;char *buffer;struct stat st;if(argc!=3){printf("Error:parameter wrong!\n");exit(0);}fd=open(argv[1],O_RDONLY);if(fd<0){printf("Error:can't open the read-file!\n");exit(0);}stat(argv[1],&st);fsize=st.st_size;buffer=(char *)malloc((1+fsize)*sizeof(char));if(!buffer){printf("Error:memory wrong!\n");exit(0);}read(fd,buffer,fsize);close(fd);fd=open(argv[2],O_WRONLY|O_CREAT);if(fd<0){printf("Error:can't open the write-file!\n");exit(0);}write(fd,buffer,fsize);close(fd);free(buffer);return 0;
}
運行結果
歡迎留言交流。。。。