For those who may follow:
This searched for file "./input.txt" in my working directory. This code worked on my g++ compiler:
code:
Quote:
#include <iostream>
#include <fstream>
using namespace std;
int main ()
{
char filename1[] = "./input.txt";
ifstream inFile (filename1);
if (inFile.fail())
{
cout << "Could Not Open File: " << filename1 << "\n";
}
else
{
cout << "File: " << filename1 << " exists and can be opened.\n";
}
return 0;
}
|
and the code that Cedar suggested worked when I used it this way. This code finds "./fstream2.cpp" in my working directory:
Quote:
#include <iostream>
#include <fstream>
using namespace std;
int main ()
{
char filename1[] = "./fstream2.cpp";
ifstream inFile;
inFile.open (filename1);
if (inFile.fail())
{
cout << "Could Not Open File: " << filename1 << "\n";
}
else
{
cout << "File: " << filename1 << " exists and can be opened.\n";
}
return 0;
}
|
I too am new at C++ and after reading this post I wanted to share what I learned by applying the tips I researched here. I noticed that this snippet of code could be changed to a function that could return a numeric value that indicates if a file exists in the directory. (1) if it exists or (0) if it does not. This code also worked for me. Although I don't believe it is the most elegant and there exists the possibility that there is a similar function in the std library to do this. Here it is anyway:
Quote:
#include <iostream>
#include <fstream>
using namespace std;
int FileExists( char *filename);
int main ()
{
char filename[] = "./fileexists.cpp";
if (FileExists(filename) == 0)
{
cout << "Could Not Open File: " << filename << "\n";
}
else
{
cout << "File: " << filename << " exists and can be opened.\n";
}
return 0;
}
int FileExists( char *filename)
{
ifstream inFile (filename);
if (inFile.fail())
return 0;
else
return 1;
cout << "Function fileexists encounted a line of code that should ";
cout << "have been impossible to reach.\n \n";
}
|
GL to all coders,
--- Escale