-
Connecting to file
I'm trying to connect to a file named accountTransactions.txt that is saved on my computer. I have set up an error trap that closes the program if the file doesn't connect properly. Everytime I try to run the program it says it can't connect to the input file and closes. When I comment the input file out and just leave the output file it connects fine. Anyone have any ideas?
infile.open("accountTransactions.txt");
if(infile.fail())
{
cout << "Input file (accountTransactions.txt) failed to open.";
exit(1);
}
outfileCheck.open("checkingSummary.txt");
if(outfile.fail())
{
cout << "Output file (checkingSummary.txt) failed to open.";
exit(1);
}
-
You probably dont have the file accountTransactions.txt in the program's working directory. You can be sure by including the entire file path name. For instance:
Code:
infile.open("C:\\temp\\accountTransactions.txt");
-
I did a test on the default values of .open for ifstream, and here's what I found out.
ifstream::open actually takes two parameters, a filename and a flag stating how to open the file.
From my knowledge, the default ofstream file open flag is:
filebuf::openprot
which in binary as bits is:
0000 0001 1010 0100
And then you've got the nocreate member of ios, which in binary is:
0000 0000 0010 0000
And you'll notice that the 6th bit on each one is set to true, meaning in the default openprot flag, it will not open the file if it doesn't exist. There are also 2 other flags set, but I'll leave that to you to figure out what the other defaults are.
However, to avoid this, I'd suggest making sure you pass a second variable to the function as the flag, something like ios::in and that way if the file doesn't exist, it will automatically create one.
I'm not sure if this is the desired effect, but maybe what's going wrong is you're trying to open a file that doesn't exist, causing your program to terminate.
-Hope that helps
-
this way may be fine:
Code:
fstream infile,outfile;
infile.open("accountTransactions.txt",fstream::in);
if(!infile.is_open())
{
cout << "Input file (accountTransactions.txt) failed to open.";
exit(1);
}
outfileCheck.open("checkingSummary.txt",fstream::out);
if(!outfile.is_open())
{
cout << "Output file (checkingSummary.txt) failed to open.";
exit(1);
}
-
I figured it out. Didn't have the txt file in the program file