linux系统下实现文件复制:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#define BUFSIZE 512
void copy(char *from, char *to){
int fromFd = -1, toFd = -1;
ssize_t nread;
char buf[BUFSIZE];
if ((fromFd = open(from, O_RDONLY)) == -1){
perror("open");
exit(1);
}
if ((toFd = open(to, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR)) == -1){
perror("open to");
exit(1);
}
nread = read(fromFd, buf, sizeof(buf));//从frmoFd中读sizeof(buf)个字节到buf
while (nread > 0){
if (write(toFd, buf, nread) != nread){
printf("write %s error\n", to);//一般不会出错
}
nread = read(fromFd, buf, sizeof(buf));
}//nread == 0 则代表读完
if (nread == -1){
printf("write %s error\n", to);
}
close(fromFd);
close(toFd);
}
int main(int argc, char **argv){
if (argc != 3){
printf("Usage : program fromFileName toFileName\n");
exit(1);
}
copy(argv[1], argv[2]);//argcv[]对应从命令行输入的命令
return 0;
}