主要函数
- int open(const char *pathname, int flags, mode_t mode);/ int open(const char *pathname, int flags);
- ssize_t read(int fd, void *buf, size_t count);
- ssize_t write(int fd, const void *buf, size_t count);
- off_t lseek(int fd, off_t offset, int whence);
概述
使用LinuxC库中函数对文件进行操作。首先打开被复制文件读取其中的内容,再创建目标文件将复制在内存buf中的文件内容写入,最后关闭两个文件。其中包括参数个数判断,文件存在判断。巧妙使用lseek函数返回值来计算被复制文件的大小,避免了不必要的空间使用。
代码
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "stdio.h"
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int main(int argc, char **argv){
int fid = 0; //descriptor of original file
int f2id = 0; //descriptor of target file
int filesize = 0;
/*check the num of main parameters*/
if(argc > 3){
printf("too much arguments after %s\n",argv[2]);
exit(-1);
}
else if(argc <3){
printf("missing argument!\n");
exit(-1);
}
/*determing if the file exist*/
fid = open(*(argv+1),O_RDWR, 0600);
if(fid < 0 ){
printf("no such file: %s\n",argv[1]);
exit (-1);
}
filesize = lseek(fid, 0, SEEK_END); //calculate the file size
char *buf = (char *)malloc(sizeof(char)*filesize); //allocate space according to the file size
lseek(fid, 0, SEEK_SET); //NOTE: pointer back to the beginning of the file in order to read the content
read(fid, buf, filesize);
/*write the content to target file*/
if(open(argv[2],O_RDWR) > 0){ //NOTE: process content when condition is non-zero, and the return value is -1 as file not exist
printf("file %s exist!\n",argv[2]);
exit(-1);
}else{
f2id = open(argv[2], O_RDWR | O_CREAT | O_TRUNC | O_EXCL, 0600);
write(f2id,buf,filesize);
printf("done!\n");
}
close(fid);
close(f2id);
return 0;
}