使用系统IO实现一个带覆盖检测的cp命令

使用系统IO实现一个带覆盖检测的cp命令
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<errno.h>
#include<unistd.h>

int find(const char*test)
{
	FILE *fp=fopen(test,"rb");
	if(fp==NULL)
	{
		perror("fp");
		return 1;
	}
	fseek(fp,0,SEEK_END);
	long size=ftell(fp);
	fclose(fp);
	return size;
}





int copy_file(char *src_file,char *dest_file)
{
	//是否覆盖
	int dest_find=open(dest_file,O_RDONLY);
	if(dest_find!=-1)
	{
		char choice;
		printf("%s,是否要覆盖(y/n)",dest_file);
		scanf("%c",&choice);
		if(choice!='y'&&choice!='Y')
		{
			printf("%s,文件未被覆盖",dest_file);
			return 1;	
		}
	}
	
	//打开文件
	int src_find=open(src_file,O_RDONLY);
	if(src_find<0)  
	{
		perror("src_find");
		return 1 ;
	}
	 dest_find=open(dest_file,O_WRONLY|O_CREAT | O_TRUNC, S_IRUSR| S_IWUSR|S_IRGRP|S_IROTH);
	if(dest_find<0)
	{
		perror("dest_file");
		return 1;
		
	}
	
	int a=find(sc_file);
 	char buff[a];
	
	a=read(src_find,buff,a));
	write(dest_find,buff,a);
	close(src_find);
	close(dest_find);
	
	if(a<0)
	{
		perror("a");
		return 1;
	}
	return 0;
}



int main(int argc, char* argv[])
{
	if(argc!=3)
	return 1;
	copy_file(argv[1],argv[2]);
		
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Linux中,可以使用文件IO的方式来实现cp命令的复制功能。具体步骤如下: 1. 打开源文件和目标文件,可以使用open()函数,如下所示: ``` int src_fd = open("source_file", O_RDONLY); int dest_fd = open("destination_file", O_WRONLY|O_CREAT, S_IRUSR|S_IWUSR); ``` 其中,第一个参数为文件名,第二个参数为打开文件的模式,第三个参数为文件权限。 2. 读取源文件的内容并写入目标文件中,可以使用read()和write()函数,如下所示: ``` char buffer[1024]; int read_size = 0; while((read_size = read(src_fd, buffer, sizeof(buffer))) > 0) { write(dest_fd, buffer, read_size); } ``` 其中,第一个参数为文件描述符,第二个参数为读取或写入的缓冲区,第三个参数为缓冲区的大小。 3. 关闭源文件和目标文件,可以使用close()函数,如下所示: ``` close(src_fd); close(dest_fd); ``` 完整代码如下所示: ``` #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <sys/stat.h> int main(int argc, char *argv[]) { if(argc != 3) { printf("Usage: %s <source_file> <destination_file>\n", argv[0]); return 1; } int src_fd = open(argv[1], O_RDONLY); if(src_fd < 0) { printf("Failed to open source file: %s\n", argv[1]); return 1; } int dest_fd = open(argv[2], O_WRONLY|O_CREAT, S_IRUSR|S_IWUSR); if(dest_fd < 0) { printf("Failed to open destination file: %s\n", argv[2]); close(src_fd); return 1; } char buffer[1024]; int read_size = 0; while((read_size = read(src_fd, buffer, sizeof(buffer))) > 0) { write(dest_fd, buffer, read_size); } close(src_fd); close(dest_fd); return 0; } ``` 将上面的代码保存为cp.c文件,然后使用gcc编译即可生成可执行文件cp: ``` gcc cp.c -o cp ``` 使用方法: ``` ./cp source_file destination_file ``` 其中,source_file为源文件名,destination_file为目标文件名。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值