Line Counting Challenge

closed account (S6k9GNh0)
On CProgramming.com, you can find a couple of challenges. The first one inside of the Help-Free section of the challenges is a line counter.

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
#include <fstream>
#include <iostream>


int main(int argc, char* argv[])
{
	if(argc!=2)
	{
		cout<<"Input should be of the form 'count filename.txt'";
		return 0;
	}
	else
	{
		ifstream input_file(argv[1]);
		if(!input_file)
		{
			cout<<"File "<<argv[1]<<" does not exist";
			return 0;
		}
		char c;
		int count = 0;
		while(input_file.get(c))
		{
			if(c == '\n')
			{
				count++;
			}
		}
		cout<<"Total lines in file: "<<count;
	}
	return 0;
}


I personally don't like this code. Here was my example.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <fstream>
#include <iostream>

int main(int argc, char* argv[])
{
         using std::cout;

	if(argc!=2)
	{
		cout<<"Input should be of the form 'count filename.txt'";
		return 0;
	}
	else
	{
		ifstream file(argv[1], ifstream::ate);
		if (!file)
		{
			cout << "File" << argv[1] << "doesn't exist.\n"
			return 0;
		}
	}
	cout << "The file" << argv[1] << "has" << file.tellg() << "lines.\n";
	return 0;
}


Didn't compile it yet so I probably made some dunce move somewhere. But any other examples or optimizations to compare to?
Your version outputs the size of the file in a non-portable way. For example, on Windows with a file that uses CRLF as newlines, your code will count one less byte for each newline in the file.
The original code also sucks for a similar reason.
This is how I would do it:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//At this point, the file has already been read onto memory, but I don't feel
//like writing that part.
long l=/*size of the file in memory*/;
char buffer=/*file buffer*/;
long lines=0;
for (long a=0;a<l;a++){
	if (buffer[a]==10)
		lines++;
	else if (buffer[a]==13){
		lines++;
		if (buffer[a+1]==10)
			a++;
	}
}
//lines contains the lines count. 
Last edited on
closed account (S6k9GNh0)
Yeah, my code is fail sauce. It doesn't even do the right thing when I look back at the question at hand...Oh well...
Topic archived. No new replies allowed.