条件:将文件A中的内容写入文件B中。其中需要判断文件A,B是否存在。若B存在则删除以前内容,再将A中内容写入。
dd.c
/********************************************************************************* * Copyright: (C) 2014 songyong<handy_skyoutlook.com> * All rights reserved. * * Filename: dd.c * Description: This file * * Version: 1.0.0(2014年12月19日) * Author: sky <[email protected]> * ChangeLog: 1, Release initial version on "2014年12月19日 20时38分08秒" * ********************************************************************************/ #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #include <string.h> #define BUF_SIZE 128 /******************************************************************************** * Description: * Input Args: * Output Args: * Return Value: ********************************************************************************/ int main (int argc, char **argv) { char *src_file; char *dst_file; int fd_src; int fd_dst; char buf[BUF_SIZE]; int len; if(argc != 3) { printf("usage: %s [src_file] [dst_file]\n", argv[0]);//不符合参数个数即报错. return -1; } src_file = argv[1]; dst_file = argv[2]; fd_src = open(src_file,O_RDONLY); if(fd_src < 0) { printf("Open file '%s' failure: %s\n",src_file,strerror(errno)); return 0; } fd_dst = open(dst_file, O_RDWR|O_CREAT|O_TRUNC,0755); if(fd_dst < 0) { printf("Open file '%s' failure: %s\n",dst_file,strerror(errno)); return 0; } while ((len = read(fd_src,buf,sizeof(buf))) > 0) { write(fd_dst,buf,len); } close(fd_src); close(fd_dst); return 0; } /* ----- End of main() ----- */
bins = dd objs = dd.o srcs = dd.c $(bins) : $(objs) gcc -o dd dd.o $(objs) : $(srcs) gcc -c dd.c clean: rm -f $(bins) (objs)
.h or .c文件 → (- c)→.o → (- o)→可执行的目标文件.
gcc:
-o output_filename,确定输出文件的名称为output_filename,同时这个名称不能和源文件同名。如果不给出这个选项,gcc就给出预设的可执行文件a.out。
-c 只编译代码生成object目标文件但不进行链接。