在Ubuntu中使用C语言实现文件的拷贝功能

思路:
a.打开源文件和目标文件;
b.读取源文件的内容,写到目标文件;
c.关闭源文件和目标文件;

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <strings.h>

#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>

int main(){
    //open file
    int fd1 = open("./cpy_test1.c",O_RDONLY); 
    int fd2 = open("./cpy_test2.c",O_WRONLY| O_CREAT| O_TRUNC,0777);
    if(fd1 == -1){//error
        perror("open");
        return -1;
    }
    printf("fd1=%d\n",fd1);
if(fd2 == -1){ //error perror("open"); return -1; } printf("fd2=%d\n",fd2);
//read file char buf[512] = {0}; int rret = read(fd1,buf,sizeof(buf)); if(rret == -1){//error perror("read"); close(fd1); return -1; } printf("rret=%d\n",rret); //write file int wret = write(fd2,buf,sizeof(buf)); if(wret == -1){ //error perror("write"); close(fd2); return -1; } printf("wret=%d\n",wret); close(fd1); //关闭源文件 close(fd2); //关闭目标文件 return 0; }

 

posted @ 2020-06-23 21:18  蜜桃李子  阅读(217)  评论(0)    收藏  举报