Skip to content

Instantly share code, notes, and snippets.

@awave1
Created January 29, 2019 21:04
Show Gist options
  • Save awave1/86fef4d374221b2e025a0f42c8e3d3bc to your computer and use it in GitHub Desktop.
Save awave1/86fef4d374221b2e025a0f42c8e3d3bc to your computer and use it in GitHub Desktop.
/**********************************************
* Last Name: Golovin
* First Name: Artem
* Student ID: 30018900
* Course: CPSC 457
* Tutorial: <your tutorial sction>
* Assignment: 1
* Question: Q4
*
* File name: countLines.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;
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
int count = 0;
while (1) {
char c;
if (read(fd, &c, 1) < 1)
break;
if (c == '\n')
count++;
}
// close file and report results
close(fd);
cout << count << " " << filename << "\n";
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment