Hi:
I'm using wxDevC++ and Vista.
I'm having a problem with file opening. I have a file called testFile.txt in the same directory as the following simple program:
#include <iostream>
#include <stdlib.h>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char *argv[])
{
ifstream infile;
infile.open("testFile.txt");
if (infile.fail())
{
cout << "file opening failed" << endl;
}
system("PAUSE");
exit (1);
}
When I run the program, I get the "file opening failed" message. I've tried variations in the code for opening the file, and they all seem to fail, although the file is clearly in the directory. For example, this code (taken from
http://www.cplusplus.com/reference/iostream/ifstream/is_open/) also produces the error-opening-file message:
// ifstream::is_open
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ifstream infile;
infile.open ("testFile.txt");
if (infile.is_open())
{
while (infile.good())
cout << "file opened successfully" << endl;
infile.close();
}
else
{
cout << "Error opening file";
}
return 0;
}
And this program also fails to open the file:
#include <iostream>
#include <stdlib.h>
#include <fstream>
#include <string>
using namespace std;
void readInputFile (ifstream &infile, char buf[]);
int main(int argc, char *argv[])
{
string fileName;
fileName= "mystring";
cout << "What is the file's name?" << endl;
cin >> fileName;
ifstream infile;
infile.open(fileName.c_str());
char buf[1024]={0};
// Read file into array
readInputFile (infile, buf);
system("PAUSE");
return 0;
}
// FUNCTION DEFINITION
void readInputFile (ifstream &infile, char buf[]) {
if (infile.is_open())
{
while (! infile.eof() )
{
infile.read(&(buf[0]),1024);
}
cout << "File reading was successful" << endl;
infile.close();
}
else cout << "Unable to open file" << endl;
}
The strange thing is that similar code worked perfectly in the same computer and the same directory a few days ago. It seems that file opening somehow has stopped working.
I suspect the problem is not the code, but something related to the directory; but what it is exactly, I have no idea.
Any suggestions? Thanks in advance.