#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream file;
file.open("file.txt");
if (file.is_open())
cout << "file opened\n";
else
cout << "file not opened\n";
}
when executed it prints <file not opened>
but when ifstream is replaced by ofstream it prints <file opened>
why does this happen can anyone tell me whats going on
If "file.txt" doesn't exist, you cannot open it for reading. Hence, <file not opened>.
However, opening "file.txt" for writing creates it on disk, so (unless something goes wrong with permissions or the disk is full, etc) it will always be <file opened>.
Try running the program with ifstream again, and you should see it work.
But isnt ifstream object provided with a constructor that calls the open() member function.If it is then shouldnt the file be opened and the read pointer be set to the beginning of the file.
Not if the file doesn't exist. Attempts to open a file for reading presuppose that the file exists to begin with. After all, what are you going to read if there isn't anything there?