linux中实现文件的复制(c代码实现)



#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
int main(){ 
        //首先打开一个文件
        int file=open("sin.txt",O_RDONLY);
        if(file==-1){//校验是否成功的打开了文件
        perror("read");//打开失败输出信息
        exit(1);//失败退出当前的程序
        } 
        //创建一个写入的文件
        int new_file=open("love.txt",O_CREAT|O_WRONLY,0777);//设置权限为777的love的txt文件
        if(new_file==-1){//校验是否成功的创建了该文件 
        perror("write");//打开失败输出信息
        exit(1);//失败退出当前的程序
        } 
        //创建一个缓冲,初始化为一
        int buff[1024]={0};
        int count=0;//初始化计数器
        count=read(file,buff,1024);//将读到的字节数组保存到缓冲数组中
        if(count==-1){
        perror("read");//文件中没有数据
        exit(1);//退出程序
        }
        while(count){//当输出为0时读取完毕
        write(new_file,buff,count);//将读取到的字节写入到文件中
        count=read(file,buff,count);//继续进行读取
        }
        close(file);//关闭文件
        close(new_file);//关闭文件
}
  • 1
    点赞
  • 32
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
复制文件可以使用系统调用函数 `open()` 、`read()` 和 `write()` ,具体步骤如下: 1. 打开源文件,使用 `open()` 函数,返回源文件文件描述符。 2. 打开目标文件,使用 `open()` 函数,返回目标文件文件描述符。 3. 从源文件读取数据并写入目标文件,使用 `read()` 函数和 `write()` 函数。 4. 关闭源文件和目标文件,使用 `close()` 函数。 下面是一个简单的示例代码: ```c #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #define BUFFER_SIZE 1024 int main(int argc, char *argv[]) { if (argc != 3) { printf("Usage: %s source_file target_file\n", argv[0]); return 1; } int source_fd = open(argv[1], O_RDONLY); if (source_fd == -1) { printf("Failed to open source file %s\n", argv[1]); return 1; } int target_fd = open(argv[2], O_WRONLY | O_CREAT | O_TRUNC, 0644); if (target_fd == -1) { printf("Failed to create target file %s\n", argv[2]); return 1; } char buffer[BUFFER_SIZE]; ssize_t n; while ((n = read(source_fd, buffer, BUFFER_SIZE)) > 0) { if (write(target_fd, buffer, n) != n) { printf("Failed to write to target file %s\n", argv[2]); return 1; } } if (n == -1) { printf("Failed to read from source file %s\n", argv[1]); return 1; } if (close(source_fd) == -1) { printf("Failed to close source file %s\n", argv[1]); return 1; } if (close(target_fd) == -1) { printf("Failed to close target file %s\n", argv[2]); return 1; } printf("File %s has been successfully copied to %s\n", argv[1], argv[2]); return 0; } ``` 移动文件可以使用 `rename()` 函数,具体步骤如下: 1. 使用 `rename()` 函数将源文件移动到目标位置。 下面是一个简单的示例代码: ```c #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { if (argc != 3) { printf("Usage: %s source_file target_file\n", argv[0]); return 1; } if (rename(argv[1], argv[2]) == -1) { printf("Failed to move file from %s to %s\n", argv[1], argv[2]); return 1; } printf("File %s has been successfully moved to %s\n", argv[1], argv[2]); return 0; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值