Windows实现方案及代码:
//add by hthe void *mmap_file(const char *fn, unsigned *_sz) { HANDLE file; HANDLE mapfile; char *data; DWORD sz; file = CreateFile( fn, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL ); if (file == INVALID_HANDLE_VALUE) return NULL; sz = GetFileSize( file, NULL ); data = NULL; mapfile = CreateFileMapping( file, // use paging file NULL, // default security PAGE_READONLY, // read/write access 0, // maximum object size (high-order DWORD) 0, // maximum object size (low-order DWORD) fn); if (mapfile == INVALID_HANDLE_VALUE) return NULL; if (sz > 0) { data = (char*)MapViewOfFile(mapfile, // handle to map object FILE_MAP_READ , // read 0, 0, sz); if (data == NULL) { fprintf(stderr, "load_file: could not allocate %ld bytes\n", sz ); sz = 0; } } CloseHandle( file ); *_sz = (unsigned) sz; return data; }
Linux实现方案及代码:
//add by hthe void *mmap_file(const char *fn, unsigned *_sz) { char *data; int sz; int fd; int errno_tmp; data = 0; fd = open(fn, O_RDONLY); if(fd < 0) return 0; sz = lseek(fd, 0, SEEK_END); if(sz < 0) goto oops; if(lseek(fd, 0, SEEK_SET) != 0) goto oops; if((data = (char*)mmap(NULL, sz, PROT_READ, MAP_SHARED, fd, 0)) == (void*)-1) goto oops; if(_sz) *_sz = sz; close(fd); return data; oops: errno_tmp = errno; close(fd); if(data != 0) free(data); errno = errno_tmp; return 0; }
时间: 2024-10-15 03:48:57