首页 > 其他分享 >C实现cp命令

C实现cp命令

时间:2022-11-20 23:55:59浏览次数:42  
标签:include 实现 newFile argv 命令 oldFile cp open size

/*
	Linux API:read,write,open
	function:C实现CP Command
*/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>	// read
#include <fcntl.h>	// open

#define MAX 100

int main(int argc, char **argv)
{
	ssize_t size = -1;
	char buf[MAX] = {0};
	
	// 打开文件
	int oldFile, newFile;	
	// if (oldFile = open(fileName, O_RDONLY) < 0) 这样的写法会阻塞,为什么?
	oldFile = open(argv[1], O_RDONLY);
	if ( oldFile < 0)
	{
		perror("Error open 1");
		exit(EXIT_FAILURE);
	} else {
        printf("open %s successfully, fd:%d\n", argv[1], oldFile);
    }
	if ((newFile = open(argv[2], O_WRONLY | O_CREAT | O_TRUNC, 0666)) < 0)
	{
		perror("Error open 1");
		exit(EXIT_FAILURE);
	} else {
        printf("open %s successfully, fd:%d\n", argv[2], newFile);
    }
	
	// 循环读写文件
	do
	{
		size = read(oldFile, buf, MAX);
		write(newFile, buf, size);
		if (size <= 0) {                         // 有效数据,指定字符长度
            printf("reach the end of file end\n");
			break;
		}
	} while(size);
	
	close(oldFile);
	close(newFile);
	exit(EXIT_SUCCESS);
}

CMakeLists.txt

cmake_minimum_required(VERSION 3.22)
message("Hello myProject")
project(myProject)
 
add_executable(myExec mainCP.c)

标签:include,实现,newFile,argv,命令,oldFile,cp,open,size
From: https://www.cnblogs.com/starcos/p/16910073.html

相关文章

  • HTML、CSS、JS实现的HTML、CSS、JS编辑器
    Atom通用代码编辑器,Github出品,基于electron​桌面应用平台,https://atom.io/,源代码:https://github.com/atom/atomVisualStudioCode通用代码编辑器,微软出品,基于electron​......
  • tcpdump抓取CoAP数据包,WireShark解析
    考虑这样的场景,设备使用NB-IoT发送CoAP数据包到服务器,服务器是Linux,作为服务器的Linux通常只有命令行。在这样的场景下想要捕获CoAP数据包进行分析。首先在设备端捕获是不现......
  • NUCLEO-F767ZI以太网功能实现笔记本电脑不开盖开机
    NUCLEO-F767ZI以太网功能实现笔记本电脑不开盖开机不想打开笔记本盖子按开机按钮开机?可以使用Wake-on-LAN远程唤醒。这里展示怎么用NUCELO-F767ZI以太网功能发送MagicPacket......
  • 工具函数实现多个组件的共同需求
    例子:验证手机号的正则表达式验证用户名是否复合规范复用度相当高的函数等等 1.定义函数一般会在src下新建untils文件夹untils=>index.js使用正......
  • dfs 实现排列型、组合型、指数型枚举
    1、排列型枚举大家喜闻乐见,经常写的全排列。不做赘述。#include<bits/stdc++.h>#defineendl'\n'usingnamespacestd;intn;intpath[20];boolvis[20];voiddfs(intste......
  • Linux 命令行批处理图片,批量去除截图的无用部分
    我希望产生一批相同区域但不同内容的截图,如果用截图工具截取矩形区域,那么每次截取的位置和大小都没法控制,不能做到区域一样。如果希望每次的截图都一样,那么就只能是保持窗口......
  • LINUX命令截图
                 ......
  • Visual C++ 6.0 Cl.exe命令启动失败解决方案
    如果想编译32位的WinC程序,选择VisualC++6.0是个不错的选择,相对VisualStudio更轻量化。一般我喜欢用命令行来生成程序,这样有时候需要批量化操作的时候更方便。安装了V......
  • LINUX命令
      ls-a列出当前目录下的所有文件,包括以.头的隐含文件(如~/.bashrc)ls–l列出当前目录下文件的详细信息2.pwd查看当前所在目录的绝对路经3.cd目录之间的移......
  • go模拟实现反向代理各种算法
    packageutiltypeHttpServerstruct{HoststringWeightint}typeLoadBalancestruct{Server[]*HttpServerCurrentIndexint}varMapWeight......