/*
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