Advertisement
falchikova_v

Untitled

May 6th, 2020
25
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.52 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <sys/types.h>
  3. #include <sys/stat.h>
  4. #include <sys/mman.h>
  5. #include <fcntl.h>
  6. #include <unistd.h>
  7. #include <sys/stat.h>
  8. #include <sys/mman.h>
  9. #include <stdio.h>
  10. #include <string.h>
  11. #include <errno.h>
  12. #include <fcntl.h>
  13. #include <unistd.h>
  14.  
  15.  
  16. int main(int argc, char * argv[]) {
  17. size_t i = 1;
  18. while (argv[i]) {
  19.  
  20. struct stat file_stat;
  21. if (stat(argv[i], &file_stat)) {
  22. fprintf(stderr, "error getting file info: %s \n", strerror(errno));
  23. printf("-1");
  24. return 1;
  25. }
  26.  
  27. off_t file_size = file_stat.st_size;
  28. if (!file_size) {
  29. printf("0\n");
  30. break;
  31. }
  32. size_t data_len = file_size / sizeof(char);
  33.  
  34. int file = open(argv[i], O_RDONLY, 0);
  35. if (file == -1) {
  36. fprintf(stderr, "error opening file info: %s \n", strerror(errno));
  37. printf("-1");
  38. return 1;
  39. }
  40.  
  41. void *mapped = mmap(
  42. NULL,
  43. file_size,
  44. PROT_READ,
  45. MAP_PRIVATE,
  46. file,
  47. 0
  48. );
  49.  
  50. char *data = mapped;
  51. size_t j = 0;
  52. size_t num_of_lines = 0;
  53. while(data[j] != EOF) {
  54. if (data[j] == '\n')
  55. num_of_lines++;
  56. j++;
  57. }
  58. if (data[j - 1] != '\n')
  59. num_of_lines++;
  60.  
  61. munmap(mapped, file_size);
  62. close(file);
  63. }
  64. return 0;
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement