How to make program run by command on terminal

Hi. I try to write a program that take a file name as an argument, and return the number of lines.
Command should like: count filename.txt, just like g++ filename.cpp -o filename
But I don't know how to do that.
When I type count filename.txt, the terminal notice: count: Command not found.
Thanks for help.
This is my code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include<iostream>
#include<fstream>

using namespace std;

int countTotalNumberOfLines(char* filename)
{
	int numberOfLines = 0;
	ifstream file(filename);
	if(!file.is_open())
	{
		//Cannot open file
		return -1;
	}
	else
	{
		char c;
		while(file.get(c))
			if(c == '\n') numberOfLines++;
	}
	file.close();
	return numberOfLines;
}
int main(int argc, char* argv[])
{
	if(argc != 2)
	{
		cout<<"Invalid input, it must be like 'count filename.txt' "<<endl;
		return 1;
	}
	int numberOfLines = countTotalNumberOfLines(argv[1]);
	if(numberOfLines == -1)
		cout<<"Cannot open file!"<<endl;
	else
		cout<<"There are/is "<<numberOfLines<<"line(s) in this file."<<endl;	
	return 0;
}
Last edited on
To run the program you have just compiled you need to precede it with:

./


So if you compiled the code with:


g++ mysource.cpp -o myprog


you would then run it with:


./myprog


and with the additional argument:


./myprog filename.txt


The

./


means look in the current folder

HTH

Andrew
Last edited on
thanks, but I dont' wat to use ./
how can I do it
Last edited on
I see. In that case you would need to put your compiled program file into a folder that is on the PATH
Thanks so much. It works
closed account (D4S8vCM9)
What's so bad with ./? :-O
Last edited on
Topic archived. No new replies allowed.