OSLab课堂作业1

时间:2023-03-08 17:49:08

 
 

日期:2019/3/16

作业:实现命令cat, cp, echo。

myecho命令

#include <stdio.h>

int main(int argc, char *argv[])

{

    int i = 0;

    printf("argument count = %d\n", argc);

    for (; i < argc; i++)

        printf("%s\n", argv[i]);

    return
0;

}

 

 
 

mycat命令

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#include <sys/stat.h>

#include <fcntl.h>

static
char buf[256] = {0};

int main(int argc, char *argv[])

{

    printf("Running program is %s\n", argv[0]);

    printf("Argument count is %d\n", argc);

    printf("File name is %s\n", argv[1]);

    int file_desc = open(argv[1], O_RDONLY);

    if (file_desc == -1)

    {

        perror("file is not existed!");

        exit(EXIT_FAILURE);

    }

    int flag = read(file_desc, buf, 255);

    while (flag != 0 && flag != -1)

    {

        printf("%s", buf);

        memset(buf, 0, sizeof(buf));

        flag = read(file_desc, buf, 255);

    }

    return
0;

}

 

 

 

 
 

mycp命令

不支持dst为目录的cp命令。

 

#include <stdio.h>

#include <stdlib.h>

#include <sys/stat.h>

#include <fcntl.h>

#include <unistd.h>

static
char buf[256] = {0};

int main(int argc, char *argv[])

{

    printf("src is %s\n", argv[1]);

    printf("dst is %s\n", argv[2]);

    int src = open(argv[1], O_RDONLY);

    if (src == -1)

    {

        perror("file doesn't exist!\n");

        exit(EXIT_FAILURE);

    }

    int dst = open(argv[2], O_RDWR | O_CREAT);

    int flag = read(src, buf, 255);

    while (flag != 0 && flag != -1)

    {

        write(dst, buf, 255);

        memset(buf, 0, sizeof(buf));

        flag = read(src, buf, 255);

    }

    return
0;

}

 

 

mycp2命令

支持dst为目录。

#include <sys/types.h>

#include <dirent.h>

#include <string.h>

#include <stdio.h>

#include <stdlib.h>

#include <sys/stat.h>

#include <fcntl.h>

#include <unistd.h>

static
char buf[256] = {0};

void cp_to_file(int src, int dst)

{

    int flag = read(src, buf, 255);

    while (flag != 0 && flag != -1)

    {

        write(dst, buf, flag);

        memset(buf, 0, sizeof(buf));

        flag = read(src, buf, 255);

    }

    close(src);

    close(dst);

}

int main(int argc, char *argv[])

{

    printf("src is %s\n", argv[1]);

    printf("dst is %s\n", argv[2]);

    int src = open(argv[1], O_RDONLY);

    if (src == -1)

    {

        perror("file doesn't exist!\n");

        exit(EXIT_FAILURE);

    }

    int dst;

    DIR *pdir = opendir(argv[2]);

    if (pdir == NULL)

    { //dst is file

        dst = open(argv[2], O_RDWR | O_CREAT);

        cp_to_file(src, dst);

    }

    else

    { //dst is dir

        printf("%s is a dir\n", argv[2]);

        char temp[256];

        strcpy(temp, argv[2]);

        if (temp[strlen(temp) - 1] != '/')

            strcat(temp, "/");

        strcat(temp, argv[1]);

        puts(temp);

        dst = open(temp, O_RDWR | O_CREAT);

        cp_to_file(src, dst);

    }

    return
0;

}