2017-11-22 7 views
0

この問題では、here誰かがファイルを使ってビットシフトを行う方法を尋ねましたが、推奨される方法はmmapを使用することでした。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); 
} 

?どのようにして乗算や加算やsubstactionなどのビットシフトやその他の算術演算を実行できますか?

ありがとうございます!

答えて

1

作業するタイプにmymapをキャストして、メモリで作業している場合のように操作できます。例えば

は、if (munmap(0,attr.st_size) == -1) {

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 
} 

又は

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) 
} 

前地図& FDを閉じた後、ファイルは、上記の操作に応じて変更されています。

関連する問題