Operating system experiment 1 linux C cp

In Section 2.3, we described a program that copies the contents of one
file to a destination file. This program works by first prompting the
user for the name of the source and destination files. Write this
program using either the Windows or POSIX API. Be sure to include all
necessary error checking, including ensuring that the source file
exists. Once you have correctly designed and tested the program, if
you used a system that supports it, run the program using a utility
that traces system calls. Linux systems provide the strace utility,
and Solaris and Mac OS X systems use the dtrace command. As Windows
systems do not provide such features, you will have to trace through
the Windows version of this program using a debugger.

#include <stdio.h>
#include <stdlib.h>    //杂项函数及其内存分布函数malloc()
#include <string.h>    //对输入的字符串进行处理
#include <sys/types.h> //size_t->int pid_t
#include <sys/stat.h>  //文件状态
#include <unistd.h>
#include <fcntl.h>
#define BUFFER_SIZE 8192
void copy(int fdin, int fdout)
{
    char buf[BUFFER_SIZE];
    size_t size;
    while (size = read(fdin, buf, BUFFER_SIZE)) // read()会把参数fdin所指的文件传送BUFFER_SIZE个字节到buf _read指针所指的内存中。返回实际读到的字节数
    {
        if (write(fdout, buf, size) != size) // write()会把参数buf所指的内存写入BUFFER_SIZE个字节到参数fdout所指的文件内。
        {
            perror("Write Error!");
            exit(1);
        }
        if (size < 0)
        {
            perror("read Error!");
            exit(1);
        }
    }
}
int main(int argc, char **argv)
{
    int fd_in = STDIN_FILENO;
    int fd_out = STDOUT_FILENO;
    if (argc != 3)
{
        printf("erro,format is:copy src dst\n");
        exit(1);
    }
    if ((fd_in = open(argv[1], O_RDONLY)) == -1)
    {
        perror("open erro");
    }
    if((fd_out=open(argv[2],O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IXUSR))==-1)
    {
        perror("create ERRO");
        exit(1);

    }
    /** O_RDONLY(只读), O_WRONLY(只写),O_RDWR(可读可写)  O_APPEND      每次写操作都写入文件的末尾
        O_CREAT        如果指定文件不存在,则创建这个文件
        O_EXCL         如果要创建的文件已存在,则返回 -1,并且修改errno的值
        O_TRUNC        如果文件存在,并且以只写/读写方式打开,则清空文件全部内容
        O_TRUNC 若文件存在,则长度被截为0,属性不变*/
    copy(fd_in, fd_out);
    close(fd_in);
    close(fd_out);
    return 0;
}     

Guess you like

Origin blog.csdn.net/weixin_50925658/article/details/124040635