0
#include <fstream>
#include <iostream>
//Bear in mind that the text file is already in the resources file
int main()
{ 
      ifstream file("Hamlet.txt", ios::in);//open file
      if (file.is_open() == true) cout << "File is open" << endl;
      else if (file.is_open() == false) cout << "File isnt open" << endl;
      return 0;
}

So I'm trying to see if the file is open or not, the text file is in the resources file so as far as I know the path of the file can be written as "Hamlet.txt" . I keep getting File isnt open, what may be the reason? Can anyone bring an explanation to this? Thanks in advance

Claudio
  • 10,614
  • 4
  • 31
  • 71
  • 1
    is the txt file in the directory in which you run the executable (i.e. the working directory)? – Borgleader Dec 09 '15 at 12:10
  • 1
    http://stackoverflow.com/questions/24097580/ifstreamis-open-vs-ifstreamfail related to checking and you might want to use experimental::filesystem::exists({"Hamlet.txt"}) to check if path exists (or boost::filesystem if you're not on latest msvc). – MojaveWastelander Dec 09 '15 at 12:22
  • 1
    Are you talking about Win32 resource files? – Simple Dec 09 '15 at 12:46
  • `ifstream file("Hamlet.txt", ios::in);` will open a file named `Hamlet.txt` that exists in the current working directly (and nothing else). You mention "resources", so what kind of resources are you talking about? – crashmstr Dec 09 '15 at 13:08

2 Answers2

2

If you are talking about Win32 resource files, you can't open your file like that. You need to use the resource API:

HRSRC const rsrc = FindResource(nullptr, MAKEINTRESOURCE(HAMLET), RT_STRING);
HGLOBAL const resource = LoadResource(nullptr, rsrc);
void const* const data = LockResource(resource);
// Use your data here.

HAMLET is a preprocessor macro used to identify your "Hamlet.txt" file from the .rc file.

Simple
  • 13,992
  • 2
  • 47
  • 47
0

The problem is that you need to run the executable in the same directory where Hamlet.txt lives. This is a big problem in C++, so typically you'll give the absolute path to the file, so you might do something like this:

ifstream file("/path/to/Hamlet.txt", ios::in);

A few other notes: the file is either open, or it's not. Thus, you don't need else if, you can simply use else. Additionally, you can use non-falsey values to indicate true; so you don't need to check == true (though it's more explicit). You could just check if(file.is_open()), which I think is more readable.

Putting these suggestions together, here's what you can do:

#include <fstream>
#include <iostream>

int main()
{ 
      ifstream file("/absolute/path/to/Hamlet.txt", ios::in);
      if (file.is_open()) {
        std::cout << "File is open" << std::endl;
      } else {
        std::cout << "File isnt open" << std::endl;
      }
      return 0;
}
erip
  • 16,374
  • 11
  • 66
  • 121