2017-11-22 6 views
0

이 호에서는 here 누군가가 파일로 비트 시프트하는 법을 물었고 제안 된 방법은 mmap을 사용하는 것이 었습니다.Mmap은 파일 내용에 액세스하고 산술 연산을 수행합니다.

지금이 내 mmap에 있습니다 :

#include <errno.h> 
#include <fcntl.h> 
#include <sys/mman.h> 
#include <sys/stat.h> 
#include <sys/types.h> 
#include <stdio.h> 
#include <unistd.h> 
#include <string.h> 
#include <stdlib.h> 
#include <signal.h> 

extern int errno; 

int main(int argc, char *argv[]) { 
    int fd; 
    void *mymap; 
    struct stat attr; 

    char filePath[] = "test.txt"; 
    fd = open(filePath, O_RDWR); 
    if (fd == -1) { 
     perror("Error opening file"); 
     exit(1); 
    } 
    if(fstat(fd, &attr) < 0) { 
     fprintf(stderr,"Error fstat\n"); 
     close(fd); 
     exit(1); 
    } 
    mymap = mmap(0, attr.st_size, PROT_READ|PROT_WRITE, MAPFILE|MAP_SHARED, fd, 0); 

    if(mymap == MAP_FAILED) { 
     fprintf(stderr, "%s: Fehler bei mmap\n",strerror(errno)); 
     close(fd); 
     exit(1); 
    } 

    if (munmap(0,attr.st_size) == -1) { 
     fprintf(stderr, "%s: Error munmap\n",strerror(errno)); 
     exit(0); 
    } 
    if (close(fd) == -1) { 
     perror("Error while closing file"); 
    } 
    exit(0); 
} 
내가 mmap에 내부의 데이터에 액세스 할 수있는 방법을

? 어떻게 비트 시프트 또는 곱셈 또는 더하기 또는 substaction 등과 같은 다른 산술 연산을 수행 할 수 있습니까?

감사합니다.

답변

1

mymap을 작업 할 유형으로 캐스팅하고 메모리에서 작업하는 것처럼 작업을 수행 할 수 있습니다. 예컨대

지도 & FD를 닫으면

char *str = (char *)mymap; 
int i; 
for(i=0 ; i<attr.st_size ; i++) { 
    str[i] += 3; // add 3 to each byte in the file 
} 

if (munmap(0,attr.st_size) == -1) { 전 또는

for(i=0 ; i<attr.st_size - 1 ; i+=2) { 
    str[i] *= str[i+1]; // multiply "odd" chars with the next one 
    str[i] >>= 2;  // shift 2 (divide by 4) 
} 

, 파일은 전술 한 동작에 따라 변화했다.

관련 문제