Linux系统调用 file-cp.c

本文介绍了一个通过系统调用来实现文件复制的程序。该程序首先读取源文件的内容到内存中,然后将这些内容写入目标文件。如果目标文件不存在,则创建新文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*Using system call implementation file copy function:
  Manual input source file target file pathname pathname
  If the destination does not exist, create and write*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
        
/*Handle source file*/
char* source_file(const char* pathname)
{
    size_t length;
    int fd;
    char* buf = NULL;
    if(access(pathname,F_OK) == -1)
    {
        perror("Error! The source file doesn't exist");
        exit(1);
    }
    if((fd=open(pathname,O_RDWR)) < 0)
    	{
                printf("Open %s failure!/n",pathname);
    		exit(1);
    	}
    length = lseek(fd, 0, SEEK_END);
    lseek(fd, 0, SEEK_SET);
    buf = (char*)malloc(length*(sizeof(char)));
    read(fd, buf, length);
    printf("%s",buf);
    close(fd);
    return buf;
}

/*Handle object file*/
void object_file(const char* pathname, char* source_buf)
{
    int fd;
    if((fd=open(pathname, O_CREAT|O_RDWR, 0777)) < 0)
    {
        printf("Open %s failure!/n",pathname);
        exit(1);
    }
    write(fd, source_buf, (strlen(source_buf)+1));
    close(fd);
}

/*The main function*/
int main(int argc, char* argv[])
{
    char* source_path = (char*)malloc(30*(sizeof(char)));
    char* object_path = (char*)malloc(30*(sizeof(char)));
    char* source_buf = NULL;
    puts("Please input the source file pathname:");
    scanf("%s",source_path);
    puts("Please input the object file pathname:");
    scanf("%s",object_path);
    source_buf = source_file(source_path);
    object_file(object_path, source_buf);
    free(source_path);
    free(object_path);
    free(source_buf);    
    return 0;					
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值