mmap是什么?
可以把文件映射到内存,也可以把内存写到文件
接下来我们看看用C++如何写入吧:
#ifndef MMAP_MMMAP_H
#define MMAP_MMMAP_H
#include <string>
#include <sys/mman.h>
#include <unistd.h>
#include <string>
#include <fcntl.h>
using namespace std;
class MMAPOperation{
public:
void readFile();
void writeFile(string data);
};
#endif
接着看看CPP:
#include "mmmap.h"
void MMAPOperation::readFile() {
printf("readFile\n");
int fd = open("output.txt", O_RDONLY);
int len = lseek(fd, 0, SEEK_END);
char *addr = (char *) mmap(NULL, len, PROT_READ, MAP_PRIVATE, fd, 0);
close(fd);
char *data = (char *)malloc(sizeof(char)*len);
memcpy(data, addr, len);
printf("readFile content is %s \n",data);
munmap(addr, len);
free(data);
}
void MMAPOperation::writeFile(string data) {
printf("writeFile %s\n",data.c_str());
int len = data.length();
int fd = open("output.txt", O_RDWR | O_CREAT, 00777);
len = lseek(fd, len, SEEK_END);
write(fd, "", 1);
char *addr = (char *) mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
close(fd);
memcpy(addr, data.c_str(), len);
munmap(addr, len);
}
接着我们写main方法跑一下:
#include <iostream>
#include "mmmap.h"
int main() {
std::cout << "Hello, World!" << std::endl;
auto* mmapOperation = new MMAPOperation();
mmapOperation->writeFile("hello world");
mmapOperation->readFile();
delete mmapOperation;
return 0;
}
print结果:
Hello, World!
writeFile hello world
readFile
readFile content is hello world
|