Sin*_*ina 8 c++ linux command bitwise-operators
我想在Linux上的文件上做一些按位操作(例如xor两个文件),我不知道如何做到这一点.是否有任何命令?
任何帮助将不胜感激.
您可以使用mmap映射文件,对映射的内存应用按位操作,然后将其关闭.
或者,将块读取到缓冲区中,对缓冲区应用操作,并写出缓冲区也可以.
这是一个例子(C,而不是C++;因为除错误处理之外的所有内容都是相同的)反转所有位:
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
int main(int argc, char* argv[]) {
if (argc != 2) {printf("Usage: %s file\n", argv[0]); exit(1);}
int fd = open(argv[1], O_RDWR);
if (fd == -1) {perror("Error opening file for writing"); exit(2);}
struct stat st;
if (fstat(fd, &st) == -1) {perror("Can't determine file size"); exit(3);}
char* file = mmap(NULL, st.st_size, PROT_READ | PROT_WRITE,
MAP_SHARED, fd, 0);
if (file == MAP_FAILED) {
perror("Can't map file");
exit(4);
}
for (ssize_t i = 0;i < st.st_size;i++) {
/* Binary operation goes here.
If speed is an issue, you may want to do it on a 32 or 64 bit value at
once, and handle any remaining bytes in special code. */
file[i] = ~file[i];
}
munmap(file, st.st_size);
close(fd);
return 0;
}
Run Code Online (Sandbox Code Playgroud)