写一份内存映射 I/O完整源码
时间: 2023-07-31 21:07:40 浏览: 101
下面是一份简单的内存映射 I/O 的完整源码:
```c++
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
using namespace std;
int main(int argc, char* argv[]) {
int fd;
struct stat sb;
off_t len;
char *p;
if (argc < 2) {
cerr << "Usage: " << argv[0] << " <file>" << endl;
exit(EXIT_FAILURE);
}
fd = open(argv[1], O_RDONLY);
if (fd == -1) {
perror("open");
exit(EXIT_FAILURE);
}
if (fstat(fd, &sb) == -1) {
perror("fstat");
exit(EXIT_FAILURE);
}
if (!S_ISREG(sb.st_mode)) {
cerr << argv[1] << " is not a file" << endl;
exit(EXIT_FAILURE);
}
p = (char*) mmap(NULL, sb.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
if (p == MAP_FAILED) {
perror("mmap");
exit(EXIT_FAILURE);
}
if (close(fd) == -1) {
perror("close");
exit(EXIT_FAILURE);
}
for (len = 0; len < sb.st_size; len++) {
putchar(p[len]);
}
if (munmap(p, sb.st_size) == -1) {
perror("munmap");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
```
这份代码实现了将指定的文件进行内存映射,然后将文件内容输出到标准输出。具体实现细节可以参考代码注释。
阅读全文