Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


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

indication about non existence of a file

Question:
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);
	if(m_fFile.***)
		return FALSE;
	else 
		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?

Answer:
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;
        else 
         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.

 

 

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