mmap-read.C 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <fcntl.h>
  4. #include <sys/mman.h>
  5. #include <sys/stat.h>
  6. #include <time.h>
  7. #include <unistd.h>
  8. #define FILE_LENGTH 0x100
  9. /* Возвратить случайное число из диапазона [low, high]. */
  10. int random_range (unsigned const low, unsigned const high) {
  11. unsigned const range = high - low + 1;
  12. return low + (int) (((double) range) * rand () / (RAND_MAX + 1.0));
  13. }
  14. int main (int argc, char* const argv[]) {
  15. int fd;
  16. // void* file_memory;
  17. char *file_memory;
  18. /* Инициализируем генератор случайных чисел. */
  19. srand (time (NULL));
  20. struct stat statbuf;
  21. /* Открываем(создаем) файл, достаточно большой, чтобы хранить целое
  22. число без знака. */
  23. fd = open (argv[1], O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
  24. fstat(fd, &statbuf);
  25. // lseek (fd, FILE_LENGTH+1, SEEK_SET);
  26. // write (fd, "", 1);
  27. // lseek (fd, 0, SEEK_SET);
  28. /* Создаем отображение в памяти. */
  29. // file_memory = (char*) mmap (0, statbuf.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
  30. file_memory = (char*) mmap (0, FILE_LENGTH , PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
  31. close (fd);
  32. // printf ("size = %d \n", &statbuf.st_size);
  33. // return 0;
  34. int b;
  35. // char b = 0;
  36. for (int i = 0; i < FILE_LENGTH; i+= 0x4 ) {
  37. b = *(int *)&file_memory[i];
  38. printf ("I am hear \n i = %i \n", i);
  39. // scanf (file_memory, "%d", &b);
  40. printf ("b = %d \n", b);
  41. }
  42. /* Освобождаем память. */
  43. munmap (file_memory, FILE_LENGTH);
  44. return 0;
  45. }