Mar 21, 2013 at 4:34pm UTC
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 Mar 21, 2013 at 4:41pm UTC
Mar 21, 2013 at 4:55pm UTC
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:
and with the additional argument:
The
means look in the current folder
HTH
Andrew
Last edited on Mar 21, 2013 at 4:56pm UTC
Mar 21, 2013 at 4:58pm UTC
thanks, but I dont' wat to use ./
how can I do it
Last edited on Mar 21, 2013 at 4:58pm UTC
Mar 21, 2013 at 4:59pm UTC
I see. In that case you would need to put your compiled program file into a folder that is on the PATH
Mar 21, 2013 at 6:51pm UTC
What's so bad with ./ ? :-O
Last edited on Mar 21, 2013 at 6:51pm UTC