Vasilii Ruzov
Vasilii Ruzov

Reputation: 554

How to get fixed size buffer from mmap area in C?

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.

Upvotes: 0

Views: 1009

Answers (3)

Davide Berra
Davide Berra

Reputation: 6568

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;
}

Upvotes: 0

zwol
zwol

Reputation: 140796

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.

Upvotes: 1

nneonneo
nneonneo

Reputation: 179612

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);

Upvotes: 2

Related Questions