c语言copy函数兑现
c语言copy函数实现
#include <stdio.h> #include <stdlib.h> #include <string.h> #include<unistd.h> #include<sys/types.h> #include<sys/stat.h> #include<fcntl.h> int readFile(char *fname,char *buff); int writeFile(char *fname,char *buff); int main(int argc,char *argv[]) { FILE *fd; int i; int ch; char *buf = NULL; buf = (char*)malloc(sizeof(char)*1024*1000*20); if(argc != 3) { printf("Usage copy source dest\n"); exit(1); } if(access(argv[1],R_OK|F_OK) < 0) { printf("%s cannot read or file not found!",argv[1]); exit(1); } if(strcmp(argv[1],argv[2]) == 0) { printf("%s cannot copy the same file!",argv[1]); exit(1); } readFile(argv[1],buf); writeFile(argv[2],buf); } /** 读源文件 **/ int readFile(char *fname,char *buff) { FILE *fp; char ch; int i=0; if((fp=fopen(fname,"rb")) == NULL) { perror("open log file error"); return -1; } while(!feof(fp)) { ch=fgetc(fp); buff[i]=ch; i++; } buff[i] = '\0'; fclose(fp); return 0; } /** 写入目标文件 **/ int writeFile(char *fname,char *buff) { int fd; size_t len; if((fd = open(fname,O_WRONLY|O_CREAT|O_TRUNC,S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH)) < 0) { perror("open log file error"); return -1; } len = strlen(buff); printf("%c",len); if(write(fd,buff,(int)len) < 1) { perror("write log error"); return -1; } close(fd); return 0; }