0

I want to do next: I have a huge file(over 4GB). I want to mmap it and then to take from this mmapped area buffers of 128 bytes. how can I do it? To mmap file I use this:

int fd = open(file_name, O_RDONLY);
void* addr = mmap(0, /*ULONG_MAX*/100000000, PROT_READ, MAP_SHARED, fd, 0);

After these strings I want to get described above buffers but I don't know how and I didn't find it in the web.

additional info: file_name is text file. it contains strings

UPD: I'll try to explain: I want to mmap file and then take from mmapped area 128 bytes(actually chars) and put it to some buffer. Now i use next code:

char buffer[128];
struct str* addr = mmap(0, /*ULONG_MAX*/128, PROT_READ, MAP_SHARED, fd, 0);
scanf((char*)addr, "%s", buffer);
printf("%s\n", buffer);

But it doesn't work. So I'm looking for the solution.

Vasilii Ruzov
  • 554
  • 1
  • 10
  • 27
  • `after these strings I want to get described above buffers` *SYNTAX ERROR*. Please elaborate/explain ... – wildplasser Apr 10 '13 at 15:03
  • I don't understand what you mean by "take from this mmapped area buffers of 128 bytes". Can you please show any code you have already written for *that*, since that is the part that doesn't work? – zwol Apr 10 '13 at 15:06
  • For the record, I don't see anything obviously wrong with the `mmap` call itself, except that some systems may object to 100000000 not being a multiple of `sysconf(_SC_PAGESIZE)`. – zwol Apr 10 '13 at 15:06
  • I don't get it... you need the first 128 bytes of that file? – Davide Berra Apr 10 '13 at 15:12
  • @DavideBerra, yes. Then I need the second 128 bytes. And so on – Vasilii Ruzov Apr 10 '13 at 15:13
  • Ok @VasiliiRuzov i've proposed my solution – Davide Berra Apr 10 '13 at 15:23

3 Answers3

2

After you successfully mmap, the file's contents (up to the mmap'd size) are available in the memory region pointed to by addr. So you can just do

memcpy(buffer, addr, 128);
nneonneo
  • 171,345
  • 36
  • 312
  • 383
1

Oh, okay, this isn't really a problem with mmap, it's a problem with scanf. That's easy. Don't use scanf. To copy fixed blocks of 128 bytes out of an mmap area into another buffer, you want memcpy.

...
unsigned char *addr = mmap(0, /*ULONG_MAX*/100000000, PROT_READ, MAP_SHARED, fd, 0);
unsigned char buf[128];
...
memcpy(buf, addr + offset, 128);

and that's all there is to it.

Community
  • 1
  • 1
zwol
  • 135,547
  • 38
  • 252
  • 361
0

If you want to print every block of 128 chars do this

char buf[129];

// put a nul char to ensure the string will be terminated
buf[128] = '\0';

// other stuff you've done
....

// get the file mapped to addr memory pointer
void* addr = mmap(0, /*ULONG_MAX*/100000000, PROT_READ, MAP_SHARED, fd, 0);

long i = 0

while (i < 100000000)
{
    // copy out the 128 bytes of the block
    memcpy(buf, (char *) &addr[i], 128);

    // print it out
    printf("BUF: %s\n", buf);

    // move to the next block
    i += 128;
}
Davide Berra
  • 6,387
  • 2
  • 29
  • 50