8.文件管理

2020-03-22  本文已影响0人  陈忠俊

1.cat命令

#include<stdio.h>
#include<fcntl.h>
#include<unistd.h>
#include<string.h>
#define E_MSG(str, val) do{perror(str); return (val);}while(0)

int main(int argc, char *argv[]){
    char buf[128];
        int r;
        int fd = open(argv[1], O_RDONLY) ;
        if(fd == -1) E_MSG("OPEN", -1);
        while((r = read(fd, buf, 128)) > 0){
                write(1, buf, r);
        }
        close(fd);
        return 0;
}

  1. copy命令的实现
    输入文件通过argv[1],输出保存到argv[2]。若目标文件不存在,创建一个新的,存在,清空文件内容,并复制新的内容。
#include<stdio.h>
#include<file.h>

int cp_file(int src_fd, int dst_fd){
        int total = 0;
        int m_read, m_write;
        char buff[128];
        while((m_read = read(src_fd, buff, 128)) > 0){
                char *temp = buff;
                while(m_read > 0){
                        m_write = write(dst_fd, temp, m_read);
                        m_read = m_read - m_write;
                        total += m_write;
                }
        }
        return total;
}

int main(int argc, char *argv[]){
        //open a file with read only
        int src_fd = open(argv[1], O_RDONLY);
        //open dest file with write mode;
        //if the file not exits, create a new one with mode 644;
        //if the file exist, empty it
        int flags = O_WRONLY|O_CREAT|O_TRUNC;
        int dst_fd = open(argv[2], flags, 0644);
        if(src_fd == -1 | dst_fd == -1) return "-1";
        cp_file(src_fd, dst_fd);
        close(src_fd);
        close(dst_fd);
        return 0;
}

  1. 文件描述符的复制
    输入的文件通过argv[1]。文件不存在,创建一个新的,存在,清空文件内容。
#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[]){
    char *msg = "this is test...\n";
        //open a file with write mode, if the file is not exists, create a new one
        //if exists, trunc it
        int flags = O_WRONLY|O_CREAT|O_TRUNC;
        int fd = open(argv[1], flags, 0644);
        if(fd == -1) return -1;
        printf("%d\n", fd);
        int s_fd = dup(1); //redirect standard output 1 to s_fd = 4
        printf("%d\n", s_fd);
        dup2(fd, 1); //copy the opened file descriptor to standard output
        close(fd);
        //write to a file by standard output descriptor
        write(1, msg, strlen(msg));
        //recovre standard output to screen
        dup2(s_fd, 1);
        close(s_fd);
        write(1, msg, strlen(msg));

        return 0;
}

输出:

zhongjun@eclipse:~$ gcc direct.c -o out
zhongjun@eclipse:~$ ./out ts
3
4
this is test...

上一篇 下一篇

猜你喜欢

热点阅读