Advertisement
Guest User

Untitled

a guest
Apr 2nd, 2016
309
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.07 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <sys/types.h>
  4. #include <sys/stat.h>
  5. #include <unistd.h>
  6. #include <fcntl.h>
  7. #include <sys/mman.h>
  8.  
  9. size_t filesize(int fd)
  10. {
  11.   struct stat buffer;
  12.   int status;
  13.   status = fstat(fd, &buffer);
  14.   return buffer.st_size;
  15. }
  16.  
  17. size_t nlines(const char *file)
  18. {
  19.   size_t i, size;
  20.   size_t num_lines = 0;
  21.   int fd;
  22.   char *map;  /* mmapped file */
  23.  
  24.   fd = open(file, O_RDONLY);
  25.   if (fd == -1) {
  26.     perror("Error opening file for reading");
  27.     exit(EXIT_FAILURE);
  28.   }
  29.  
  30.   size = filesize(fd);
  31.  
  32.   map = mmap(0, size, PROT_READ, MAP_SHARED, fd, 0);
  33.   if (map == MAP_FAILED) {
  34.     close(fd);
  35.     perror("Error mmapping the file");
  36.     exit(EXIT_FAILURE);
  37.   }
  38.  
  39.   /* Read the file from the mmap */
  40.   for (i = 0; i < size; ++i) {
  41.     if(map[i] == '\n')
  42.       num_lines++;
  43.   }
  44.  
  45.   if (munmap(map, size) == -1) {
  46.     perror("Error un-mmapping the file");
  47.   }
  48.   close(fd);
  49.   return num_lines;
  50. }
  51.  
  52. int main(int argc, char *argv[])
  53. {
  54.   if(argc > 1)
  55.     printf("%s %d\n", argv[1], nlines(argv[1]));
  56.   return 0;
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement