Reputation: 21
#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
Upvotes: 0
Views: 1478
Reputation: 14420
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.
Upvotes: 2
Reputation: 16995
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;
}
Upvotes: 0