devxlogo

indication about non existence of a file

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())

See also  5 Benefits of Using Time Tracking Software
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist