Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: C++
Expertise: Beginner
Nov 9, 1999



Building the Right Environment to Support AI, Machine Learning and Deep Learning

indication about non existence of a file

Using ifstream, I want to open a file that already exists, and launch an error message if it does not exist. How can I get indication that the file that I'm trying to open does not exist?

Here is my code:

char* fileName = (char*)LPCTSTR(m_sFileName);
	m_fFile.open(name, ios::in | ios::nocreate | ios::binary);
		return FALSE;
		return TRUE;
*** What should I put here in order to get a message that the file does not exist, and not create a new file?

Before answering your specific question, a few stylistic issues. First, examine this statement:

char* fileName = (char*)LPCTSTR(m_sFileName);
Using C-style cast is better avoided in new code. Furthermore, in this case, the cast is totally uncalled for. Simply use a const char *. open() requires a const pointer anyway:

  const char* fileName = LPCTSTR(m_sFileName);
Secondly, don't mix bool variables with TRUE and FALSE macros. Use the built-in 'true' and 'false' keywords instead:

  return false; //better style
This convention is safer, self-documenting, and will save you from serious maintenance problems in the future.

Now back to your question. You can call the fail() member function to examine the success or failure state of the last operation:

	if(m_fFile.fail()) /*returns 'true' on failure*/
         return false;
         return true;
As you can see this is verbose. A better way to code this statement is:

return !(m_fFile.fail())
DevX Pro
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date