Created
January 29, 2019 21:09
-
-
Save awave1/8f95eb7e6a1da77333ef4cd0baecc015 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /********************************************** | |
| * Last Name: Golovin | |
| * First Name: Artem | |
| * Student ID: 30018900 | |
| * Course: CPSC 457 | |
| * Tutorial: T05 | |
| * Assignment: 1 | |
| * Question: Q5 | |
| * | |
| * File name: myWc.cpp | |
| *********************************************/ | |
| #include <fcntl.h> | |
| #include <iostream> | |
| #include <stdio.h> | |
| #include <stdlib.h> | |
| #include <string> | |
| #include <sys/stat.h> | |
| #include <sys/types.h> | |
| #include <unistd.h> | |
| using namespace std; | |
| const size_t CHAR_BUFFER_SIZE = 256; | |
| int main(int argc, char *const argv[]) { | |
| // get the file name from command line | |
| string filename; | |
| if (argc != 2) { | |
| cerr << "Usage: readFile <input file> " << endl; | |
| return -1; | |
| } else { | |
| filename = argv[1]; | |
| } | |
| // open the file for reading | |
| int fd = open(filename.c_str(), O_RDONLY); | |
| if (fd < 0) { | |
| cerr << "Could not open file " << filename << "\n"; | |
| exit(-1); | |
| } | |
| // read file character by character and count lines | |
| char char_buffer[CHAR_BUFFER_SIZE]; | |
| int lines = 0; | |
| while (true) { | |
| ssize_t bytes_read = read(fd, &char_buffer, CHAR_BUFFER_SIZE); | |
| if (bytes_read <= 0) { | |
| break; | |
| } | |
| for (int i = 0; i < bytes_read; i++) { | |
| if (char_buffer[i] == '\n') { | |
| lines++; | |
| } | |
| } | |
| } | |
| // close file and report results | |
| close(fd); | |
| cout << lines << " " << filename << "\n"; | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment