Advertisement
Guest User

mmap

a guest
Aug 5th, 2010
310
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.06 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <ctype.h>
  4. #include <unistd.h>
  5. #include <sys/types.h>
  6. #include <sys/stat.h>
  7. #include <sys/mman.h>
  8. #include <fcntl.h>
  9. #include <vector>
  10.  
  11. bool die(const char *s)
  12. {
  13.     perror(s);
  14.     exit(1);
  15. }
  16. int main(int argc,char **argv)
  17. {
  18.     char c;
  19.     int num=0;
  20.     int pos=1;
  21.     int line=1;
  22.  
  23.     std::vector<int> res;
  24.    
  25.     struct stat statbuf;    
  26.     int fd=open(argv[1],O_RDONLY);
  27.     (fd>0) || die("open");
  28.     (fstat(fd,&statbuf)==0) || die("stat");
  29.    
  30.     void *mem=mmap(0,statbuf.st_size,PROT_READ,MAP_SHARED,fd,0);
  31.     mem || die("mmap");
  32.     char *head=(char*)mem;
  33.     char *tail=head+statbuf.st_size;
  34.     while((c=*head++),(head<=tail))
  35.     {
  36.         if (c>='0' && c<='9')
  37.             num=num*10+c-'0';
  38.         else if (c=='-') pos=0;
  39.         else if (c=='\n')
  40.         {
  41.             num=pos?num:-num;
  42.             res.push_back(num);
  43.             num=0;
  44.             pos=1;
  45.             line++;
  46.         }
  47.         else
  48.         {
  49.             printf("I've got a problem with this file at line %d\n",line);
  50.             exit(1);
  51.         }
  52.     }
  53.     unsigned sum=0;
  54.     for (int i=0;i<res.size();i++)
  55.     {
  56.         sum=sum+(unsigned)res[i];
  57.     }
  58.     printf("=>%d\n",sum);
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement