Linux中使用C语言实现cp功能
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
int main(int argc, char *argv[])
{
int fd, fd2;
fd = open(argv[1], O_RDONLY);
if (fd < 0)
{
perror("open");
}
else
{
printf("文件打开成功!\n");
}
char buff[128] = "";
ssize_t count = read(fd, buff, sizeof(buff) - 1);
if (count < 0)
{
perror("read");
}
else
{
printf("读出的字节数为%ld\n", count);
}
fd2 = open(argv[2], O_WRONLY);
if (fd2 < 0)
{
perror("open");
}
else
{
printf("文件打开成功!\n");
}
ssize_t count2 = write(fd2, buff, strlen(buff) );
if (count2 < 0)
{
perror("write");
}
else
{
printf("写入的字节数为%ld\n", count2);
}
close(fd);
close(fd2);
return 0;
}
拿走直接可用!
|