How can one avoid opening a file that doesn't exist ?

Hello there,
I've written an object oriented program that simply counts and returns the lines of a file. The program takes a command line argument as the name of the file :
./app <filename>

It works well except that even when i give a name of a file that doesn't exist,
like :
./app ddd.txt ( ddd.txt ) doesn't exist, the out put is :

There are 17 lines in ddd.txt . even when i tried to see the characters that were compared against '\n', nothing was there.

How can i solve this ?

Here's the 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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include <iostream>
#include <string>
#include <fstream>

class LineCounter {
	std::string fileName;
public:
	LineCounter(){} // default ctor
	LineCounter(std::string fileName); // fileName initializer ctor

	void setFileName(std::string fileName); // sets the fileName data memeber
	std::string getFileName(); // returns the file name as a string
	bool valid (std::string fileName); // returns true if the file name is valid, false otherwise
	int countLines(void); // returns the number of lines in fileName file

};

int main(int argc, char* argv[]) {
	
	if( argc != 2 || argc > 2 )
	{
		std::cout << "Usage : " << argv[0] << " <filename> " << std::endl;
		return -1;
	}
	else
	{
		LineCounter counter;
		counter.setFileName((std::string)argv[1]);
		std::cout << " There are " << counter.countLines() << " lines in " << counter.getFileName() << std:: endl;
	}
	
	return 0; 
}

LineCounter::LineCounter ( std::string fileName) {
	setFileName(fileName);
}

void LineCounter::setFileName( std::string fileName) {

	if(valid(fileName)) {
		this -> fileName = fileName;
	}
	else
	{
		std::cout << " Invalid file name. "<< std::endl;
		return;
	}
}

std::string LineCounter::getFileName(void) {
	return fileName;
}

bool LineCounter::valid(std::string fileName) {
	return true; // no validation for now
}

int LineCounter::countLines(void) {
	
	int lineCount = 0; 

	std::fstream file(fileName, std::ios::in);
	
	if(file.good()) {
		while(!file.eof()) {
			if( file.get()  == '\n' ) lineCount++;

		}

		
		file.close();
		return lineCount;

	}
}
Look at the your countLines function and tell, what will be returned if file.good() expression will be false.
Oh, what a stupid bug, how could i miss that ?!!! o_O

Thanks bro :)
Topic archived. No new replies allowed.