#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <ctype.h>
#include <termios.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/ioctl.h>
#include <string.h>
#define MAP_MASK 4095UL

unsigned char buf[1024] = {0};
int main(int argc, char **argv)
{
    void *map_ , *virt_addr_start, *p_start;
    unsigned long file_size, size;
    unsigned long start;
    int fd_mem, fd_file;

    if (argc != 4) {
        printf(\"usage : ./get_file 0x33a00000 0x200000 hello\\n\");
        return -1;
    }

    start = strtol(argv[1], NULL, 16);
    file_size = strtol(argv[2], NULL, 16);
    printf(\"start : 0x%lx file_size :0x%lx \\n\", start, file_size);

    if ((fd_mem = open(\"/dev/mem\", O_RDWR | O_SYNC)) < 0) {
        perror(\"open\");
        return -1;
    }

    if ((fd_file = open(argv[3], O_RDWR | O_CREAT | O_TRUNC, 0777)) < 0) {
        perror(\"open\");
        return -1;
    }
    map_ = mmap(0, file_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd_mem, start & ~MAP_MASK);

    virt_addr_start = map_ + (start & MAP_MASK);
    p_start = virt_addr_start;
    size = 0;
    do {
        memcpy(buf, p_start, 1024);
        write(fd_file, buf, 1024);
        size += 1024;
        p_start += 1024;

    } while (size <= file_size );

    munmap(map_ , file_size);
    close(fd_mem);
    close(fd_file);
    return 0;
}

收藏 打印