写文件系统函数

该程序是一个C语言编写的简单文件复制器,它打开用户指定的源文件,读取前1024字节的内容,然后将这些内容写入目标文件。程序使用了read()和write()系统调用进行文件操作,并处理了可能的中断错误。
摘要由CSDN通过智能技术生成
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h> // Added for read() and write() functions

#define resource_mode 0
#define destination_mode 0774
#define FILESIZE 1024

int main(int argc, char *argv[])
{
    int resource_fd, destination_fd;
    char buffer[FILESIZE], *p;
    int readbytes, writebytes;

    if (argc != 3)
    {
        printf("Usage:copy from resource file to destination file\n %s src_file dest_file\n", argv[0]);
        exit(0);
    }

    if ((resource_fd = open(argv[1], resource_mode)) == -1)
    {
        perror("Can't open source file");
        exit(0);
    }

    if ((destination_fd = creat(argv[2], destination_mode)) == -1)
    {
        perror("Can't create destination file");
        exit(0);
    }

    // Read the first 1024 bytes of content into the buffer using the read function
    while ((readbytes = read(resource_fd, buffer, FILESIZE)) > 0)
    {
        p = buffer;
        if (readbytes == -1 && errno != EINTR)
            break;
        else if (readbytes > 0)
        {
            // Write the read 1024 bytes of content to the destination file using the write function
            while ((writebytes = write(destination_fd, p, readbytes)) > 0)
            {
                if (writebytes == -1 && errno != EINTR)
                    break;
                else if (writebytes == readbytes)
                    break;
                else if (writebytes > 0)
                {
                    p += writebytes;
                    readbytes -= writebytes;
                }
            }
            if (writebytes == -1)
                break;
        }
    }

    close(resource_fd);
    close(destination_fd);

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值