#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;
}
写文件系统函数
该程序是一个C语言编写的简单文件复制器,它打开用户指定的源文件,读取前1024字节的内容,然后将这些内容写入目标文件。程序使用了read()和write()系统调用进行文件操作,并处理了可能的中断错误。
摘要由CSDN通过智能技术生成