0

Can someone kindly explain how I can implemented an mread function, by using the read() system call. This method needs to read contents which are found in the mmapped file and read them into a buffer. I have access to both the mmapped file and buffer by means of pointers. (i.e. void *addr and void *buff).

Your help is v.much appreciated.

Try so far:

int fd;

if ((fd = open("file.hole",O_RDWR, "rb")) < 0) {
    perror("create .hole file error");
    exit(EXIT_FAILURE);
}

if (write(fd, addr, count)!= count) {
    perror("Cannot write from address");
    exit(EXIT_FAILURE);
}

buff = (char*)malloc(count * sizeof(char *));

if (read(fd, buff, count)) {
    perror("Cannot read from file descriptor to the buffer");
    exit(EXIT_FAILURE);
}
3
  • int fd; if((fd = open("file.hole",O_RDWR, "rb")) < 0) { perror("create .hole file error"); exit(EXIT_FAILURE); } if(write(fd, addr, count)!= count) { perror("Cannot write from address"); exit(EXIT_FAILURE); } buff = (char*)malloc(count * sizeof(char *)); if(read(fd, buff, count)) { perror("Cannot read from file descriptor to the buffer"); exit(EXIT_FAILURE); }
    – Samba693
    Jun 22, 2014 at 13:23
  • Or maybe I can assign character by character such as the following code? buff = (char*)malloc(count * sizeof(char *)); for(int i = 0; i<count; i++) { buff[i] = (char)addr[offset + i]; }
    – Samba693
    Jun 22, 2014 at 13:31
  • Possible duplicate: stackoverflow.com/questions/24350294/…
    – Damon
    Jun 22, 2014 at 18:43

1 Answer 1

0

Sorry, this might not a complete solution, but I don't have sufficient reputation to add only comments.

If you need to read data from mmaped file (assumed that you have called mmap() on a file), you don't need read() system call; you just need to copy the content from addr to buff.

If you need read() system call to copy data from a file to a buffer, you don't need mmap(); you should just do open() on the file to get an fd and then do read() data from the fd to the buffer.

2
  • So to copy the contents : would it be ok to do like this? : buff = (char*)malloc(count * sizeof(char *)); for(int i = 0; i<count; i++) { buff[i] = (char)addr[offset + i]; }
    – Samba693
    Jun 22, 2014 at 14:29
  • You can use memcpy(buff, addr, ADDR_SIZE), where the ADDR_SIZE should be known when you call mmap(). By the way, the argument passed into malloc should be "count * sizeof(char)". Jun 22, 2014 at 14:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.