Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <unistd.h>
- #include <fcntl.h>
- #include <sys/mman.h>
- size_t filesize(int fd)
- {
- struct stat buffer;
- int status;
- status = fstat(fd, &buffer);
- return buffer.st_size;
- }
- size_t nlines(const char *file)
- {
- size_t i, size;
- size_t num_lines = 0;
- int fd;
- char *map; /* mmapped file */
- fd = open(file, O_RDONLY);
- if (fd == -1) {
- perror("Error opening file for reading");
- exit(EXIT_FAILURE);
- }
- size = filesize(fd);
- map = mmap(0, size, PROT_READ, MAP_SHARED, fd, 0);
- if (map == MAP_FAILED) {
- close(fd);
- perror("Error mmapping the file");
- exit(EXIT_FAILURE);
- }
- /* Read the file from the mmap */
- for (i = 0; i < size; ++i) {
- if(map[i] == '\n')
- num_lines++;
- }
- if (munmap(map, size) == -1) {
- perror("Error un-mmapping the file");
- }
- close(fd);
- return num_lines;
- }
- int main(int argc, char *argv[])
- {
- if(argc > 1)
- printf("%s %d\n", argv[1], nlines(argv[1]));
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement