Skip to content

Instantly share code, notes, and snippets.

@surinoel
Created November 1, 2019 03:56
Show Gist options
  • Save surinoel/d536220fab9f523af533f692d30a2ec9 to your computer and use it in GitHub Desktop.
Save surinoel/d536220fab9f523af533f692d30a2ec9 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <sys/types.h>
int main(int argc, char **argv) {
int i;
int fd;
int ret;
struct stat sb;
void *ptr;
char tmp[] = "hello";
fd = open("ls.txt", O_RDWR);
if(fd < 0) {
printf("open() error\n");
return -1;
}
ret = fstat(fd, &sb);
if(ret < 0) {
printf("fstat() error\n");
close(fd);
return -1;
}
/*
void *mmap(void *addr, size_t length, int prot, int flags,
int fd, off_t offset);
int munmap(void *addr, size_t length);
*/
ptr = mmap(NULL, sb.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if(ptr == MAP_FAILED) {
printf("mmap() error\n");
close(fd);
return -1;
}
for(i=0; i<strlen(tmp); i++) {
printf("%c", *(char *)(ptr + i));
*(char *)(ptr + i) = tmp[i];
}
munmap(0, sb.st_size);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment