cp命令的实现代码
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
int main(int argc, char* argv[]) {
if (argc != 3) {
fprintf(stderr, "Usage: %s <source_file> <destination_file>\n", argv[0]);
return 1;
}
int fd = open(argv[1], O_RDONLY);
if (fd < 0) {
perror("打开源文件错误");
return 1;
}
char buf[256];
int rd = read(fd, buf, sizeof(buf));
if (rd < 0) {
perror("读取源文件失败");
close(fd);
return 1;
}
close(fd);
int fd1 = open(argv[2], O_WRONLY | O_CREAT | O_TRUNC, 0664);
if (fd1 < 0) {
perror("打开目标文件错误");
return 1;
}
int wd = write(fd1, buf, rd);
if (wd < 0) {
perror("写入目标文件错误");
close(fd1);
return 1;
}
close(fd1);
return 0;
}
pwd指令
#include<unistd.h>
#include<fcntl.h>
#include<stdio.h>
#include<stdlib.h>
int main(int argc,char*argv[])
{
char buf[256];
getcwd(buf,256);
printf("\n%s\n",buf);
return 0;
}
ls指令
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
int main(int argc,char*argv[]) {
DIR *dp;
struct dirent *sdp;
dp = opendir(argv[1]);
if(dp==NULL)
{
perror("opendir error");
exit(1);
}
int count = 0;
while((sdp= readdir(dp))!=NULL)
{
printf("%-20s\t",sdp->d_name);
count++;
if(count%5!=0)
{
continue;
}
else
{
printf("\n");
}
}
printf("\n");
closedir(dp);
return EXIT_SUCCESS;
}
cat指令
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<fcntl.h>
#include<string.h>
int main(int argc,char*argv[])
{
int n;
if(argc==4)
{
if(strcmp(argv[2],">")==0)
{
int fd1 = open(argv[3],O_RDWR|O_CREAT|O_TRUNC,0664);
if(fd1==-1)
{
perror("open error");
exit(1);
}
dup2(fd1,STDOUT_FILENO);
}
}
char buf[1024];
int fd2 = open(argv[1],O_RDONLY);
if(fd2==-1)
{
perror("open read error");
exit(1);
}
while((n=read(fd2,buf,sizeof(buf))))
{
write(STDOUT_FILENO,buf,n);
}
return 0;
}