#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/mman.h>
/*
* ./copy 1.txt 2.txt
* argc = 3
* argv[0] = "./copy"
* argv[1] = "1.txt"
* argv[2] = "2.txt"
*/
int main(int argc, char **argv)
{
int fd_old, fd_new;
struct stat stat;
char *buf;
/* 1. 判断参数 */
if (argc != 3)
{
printf("Usage: %s <old-file> <new-file>\n", argv[0]);
return -1;
}
/* 2. 打开老文件 */
fd_old = open(argv[1], O_RDONLY);
if (fd_old == -1)
{
printf("can not open file %s\n", argv[1]);
return -1;
}
/* 3. 确定老文件的大小 */
if (fstat(fd_old, &stat) == -1)
{
printf("can not get stat of file %s\n", argv[1]);
return -1;
}
/* 4. 映射老文件 */
buf = mmap(NULL, stat.st_size, PROT_READ, MAP_SHARED, fd_old, 0);
if (buf == MAP_FAILED)
{
printf("can not mmap file %s\n", argv[1]);
return -1;
}
/* 5. 创建新文件 */
fd_new = open(argv[2], O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
if (fd_new == -1)
{
printf("can not creat file %s\n", argv[2]);
return -1;
}
/* 6. 写新文件 */
if (write(fd_new, buf, stat.st_size) != stat.st_size)
{
printf("can not write %s\n", argv[2]);
return -1;
}
/* 5. 关闭文件 */
close(fd_old);
close(fd_new);
return 0;
}
![avatar](https://profile-avatar.csdnimg.cn/1dad28de79404daea521342527545fa8_m0_63168877.jpg!1)
![avatar-vip](https://csdnimg.cn/release/downloadcmsfe/public/img/user-vip.1c89f3c5.png)
妄北y
- 粉丝: 2w+
- 资源: 1万+
最新资源
- Screenshot_20250215_232252_com.tencent.tmgp.sgame.jpg
- 基于非支配排序的多目标蜣螂优化算法在IEEE33节点系统分布式电源选址定容及优化结果分析,基于非支配排序的多目标蜣螂优化算法在IEEE33节点系统中的分布式电源选址定容研究及其结果分析,基于非支配排序
- Screenshot_20250215_232238_com.tencent.tmgp.sgame.jpg
- 基于Vue框架的卡尔劳莱斯精华新材H5设计源码
- (源码)基于Dubbo框架的分布式服务示例.zip
- 基于Java和Shell的RocketMQ设计源码及涂鸦评论模块
- FactoryIO 2.5工厂流水线仿真程序:入门指南与场景实践(使用TIA Portal V15与SCL语言),FactoryIO 2.5工厂流水线仿真程序:入门者的TIA Portal V15实战
- 基于Python语言的LazyQ课程学习设计源码
- 基于WriterSide整理的数字地产项目标准化开发文档(程序篇)设计源码
- (源码)基于ESP32的音频输入开关转换器项目.zip
- 基于10kV线路的微机继电保护装置:源码、PCB图纸及BOM清单-缩短开发周期的自学素材,10kV线路微机继电保护装置源码及配套PCB图纸详解:缩短开发周期的基础工程学习素材,10kV线路微机继电保
- (源码)基于涂鸦 SDK 的微信小程序智能设备控制 Demo.zip
- 基于Matlab的4孔入式静压轴承有限差分计算程序:油膜厚度与压力分析,基于Matlab的4孔入式静压轴承有限差分计算程序:油膜厚度与压力分析,基于matlab的孔入式静压轴承程序,进油孔数为4个,采
- 基于Vue框架的管网健康评价前端设计源码
- (源码)基于ESP8266模块的RGB灯光控制器.zip
- 三菱FX5U PLC与台达DT330温控器通信控制系统的设计与实施-高效启停控制与双方向远程温度设定,三菱FX5U PLC与台达DT330温控器通信控制系统的设计与实施-远程双设定、启停控制及48
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈
![feedback](https://img-home.csdnimg.cn/images/20220527035711.png)
![feedback](https://img-home.csdnimg.cn/images/20220527035711.png)
![feedback-tip](https://img-home.csdnimg.cn/images/20220527035111.png)