PDA

View Full Version : help with file streams



omgh4x0rz
05-01-2007, 03:18 AM
How can I get the program to cout something if the specified file is not found?

For example, say I want to use infile>>something;
and declare ifstream infile("test.txt"); as the infile. Is there a boolean function somewhere that returns false if the file is not found?

duther
05-02-2007, 09:31 AM
#include <fstream>
using namespace std;

int main(void)
{
ifstream fin("hello.txt");
if(!fin)
cout << "File doesn't exist" << endl;
else
fin.close();
return 0;
}

Erik the Red
05-11-2007, 12:37 AM
#include <fstream>
#include <iostream>
#include <string>
using namespace std;

int main(void)
{
string line;
ifstream file ("Test.txt");
if(file.is_open())
{
getline (file,line);
cout << line << endl;
file.close();
}
else
{
cout << "file does not exist ";
}

system("pause");
return 0;
}


This works too