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

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

The Latest

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a

chrome os developer mode

How to Turn on Chrome OS Developer Mode

Google’s Chrome OS is a popular operating system that is widely used on Chromebooks and other devices. While it is designed to be simple and user-friendly, there are times when users may want to access additional features and functionality. One way to do this is by turning on Chrome OS

homes in the real estate industry

Exploring the Latest Tech Trends Impacting the Real Estate Industry

The real estate industry is changing thanks to the newest technological advancements. These new developments — from blockchain and AI to virtual reality and 3D printing — are poised to change how we buy and sell homes. Real estate brokers, buyers, sellers, wholesale real estate professionals, fix and flippers, and beyond may