部分系统函数实现

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 *dir;
    // struct dirent *ent;

    // dir = opendir(".");
    // if (dir == NULL) {
    //     perror("Unable to open directory");
    //     return EXIT_FAILURE;
    // }

    // while ((ent = readdir(dir)) != NULL) {
    //     printf("%s\n", ent->d_name);
    // }

    // closedir(dir);

    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;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值