实现简单cp命令

 事先需要阅读系统调用------文件操作函数

#include<stdio.h>
#include<sys/file.h>
#include<fcntl.h>
#include<sys/stat.h>
#include<stdlib.h>

void main(int argc, char *argv[])
{
    if(argc != 3)
    {
        printf("Insufficient number of parameters");
        /*
         *The return value of exit fuction isn't 0
         *representing an exception exit!
        */
        exit(1);
    struct stat stat1, stat2;    //define the stat struture variable
    stat(argv[1],&stat1);    
    stat(argc[2],&stat2);

    /*
     *Determine whether the two files are the same!
    */
    if(stat1.st_ino ==stat2.st_ino)
    {
        printf("%s and %s are the same file!", argv[1], argv[2]);
        exit(1);
    }

    //file descriptor
    int fd_a = open(argc[1], O_RDONLY);
    if(fd_a == -1)
    {
        printf("Open %s failure in reading !", argv[1]);
        exit(1);
    }
    
    int fd_b = open(argv[2], O_WRONLY|O_CREAT|O_TRUNC, 0664);
    if(fd_b == -1)
    {
        printf("Open %s failure in writing .", argc[2]);
        exit(1);
    }
    
    while(1)
    {
        char buff[128] = {0};
        int n = read(fd_a, buff, 127);
        if(n < 0)
        {
            break;
        }
        write(fd_b, buff, n);
    }
    
    close(fd_a);
    close(fd_b);
    exit(0);
}

猜你喜欢

转载自blog.csdn.net/qq_41822235/article/details/81395657
今日推荐