Skip to content

Instantly share code, notes, and snippets.

@hmyit
Forked from CoolerVoid/mmap.c
Created March 5, 2020 04:33
Show Gist options
  • Select an option

  • Save hmyit/dd831ff6530d929d19e5fbbde8a194ac to your computer and use it in GitHub Desktop.

Select an option

Save hmyit/dd831ff6530d929d19e5fbbde8a194ac to your computer and use it in GitHub Desktop.
my mmap example
#include <stdio.h>
#include <sys/mman.h>
/*
simple function use with mmap and munmap
look the man from mmap,if you have questions...
*/
// return size of bytes on file , same to unix cmd "du -b file"
long FileSize(const char *file)
{
long ret;
FILE *fh = fopen(file, "r");
if(!fh)
{
return 0;
}
fseek(fh, 0, SEEK_END);
ret = ftell(fh);
fclose(fh);
return ret;
}
/* example
to use with mmap
fd = fopen("mmap.c", "r"); str = fmmap(fd,FileSize("file.txt")); pust(str); munmap(str,sizeof(str)); fclose(fd);
*/
char *fmmap(FILE *fd,long long FileSize)
{
fd=(FILE *)fileno(fd);
return mmap(0, FileSize, PROT_READ, MAP_PRIVATE, (int)fd, 0);
}
int main() {
FILE *fd;
char *str;
fd = fopen("mmap.c", "r");
str = fmmap(fd,FileSize("mmap.c"));
puts(str);
munmap(str,sizeof(str));
fclose(fd);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment