We help IT Professionals succeed at work.

About mmap and lseek

william007 used Ask the Experts™
int f=open("myFile",O_RDONLY);
int n=lseek(f,0,SEEK_END);
void * mf=mmap(0,n,PROT_READ,MAP_PRIVATE,f,0);

1)Am I right that using lseek(f,0,SEEK_END); to get the file size will give you filesize + 1, and hence it is more correct to use lseek(f,-1,SEEK_END);? Also, is this a correct way to get the filesize?
2)After getting mf, how should I read the file inside the memory map file?
eg my file has
****myFile start****
line1 abc
line2 def
****myFile end****
How to get "line2 def", ie the second line?

Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Top Expert 2006
1. No ... Why would it give you length +1?
int n=lseek(f,0,SEEK_END);
is correct

note that this would position the head to end of file ... you must reposition it to beginning of file

2. mmap returns pointer to mmaped area ... simply treat it like a buffer in memory ... here is an example which should answer both your questions

int main() {          
      void * ret;
      int n;

      int f = open ("ha.txt", O_RDONLY);

      n = lseek (f,0,SEEK_END);
      printf ("%d\n",n);

      n = lseek (f,0,SEEK_SET);
      ret = mmap (0, 1024, PROT_READ,MAP_PRIVATE, f,0);
      printf ("%s\n", ((char *)ret) + 10);


For question 1,
this is because
I type "abcdef" in a file, it gives me length 7,
even nothing in a file, it gives me length 1,
If it is correct, what is the reason for the size? abcdef...should be 6 bytes and nothing in a file should be 0 byte....
Top Expert 2006
EOF is also part of file .. else you would never know where the file ends!!!


I see:)