iccaros Posted May 17, 2005 Report Share Posted May 17, 2005 ok I have two c++ programs to test before makeing them into function..I have one program that creates a file called salesinfo.txt and populates it with information.I have a second program that reads the file and displayes its output..my problem is.. I think the first program is not closeing the file.. I think this because I have to add examplefile.close() before I can try to read the file.you will see where I commented out the placement of examplefile.close() in the first #include <iostream>#include <fstream>#include <iomanip>using namespace std;int main (){ int Sales; char record_name[32]; ofstream examplefile ("salesinfo.txt"); if (examplefile.is_open()) { cout << "Sales Person name input: "; cin >> record_name; cout << "value of sales for the week: "; cin >> Sales; examplefile << record_name << " " << Sales; } examplefile.close(); return 0; } program two#include <iostream>#include <fstream>#include <iomanip>using namespace std;int main (){ int Sales; char record_name[8]; ifstream examplefile ("salesinfo.txt"); examplefile.close(); examplefile.open ("salesinfo.txt"); if ( !examplefile ) {cout << "Error opening file"; exit (1);} while ( ! examplefile.eof()) { //examplefile.get (record_name, 8); examplefile >> record_name >> Sales >> ws; cout << record_name << " " << "$" << Sales << endl; } examplefile.close(); return 0; } Quote Link to post Share on other sites
jcl Posted May 18, 2005 Report Share Posted May 18, 2005 They work fine here, with or without the calls to close()~/src/bt $ grep close first.cc second.cc ~/src/bt $ g++ -o first first.cc ~/src/bt $ g++ -o second second.cc ~/src/bt $ ./first Sales Person name input: foovalue of sales for the week: 12~/src/bt $ ./second foo $12~/src/bt $The files are closed implicitly when the program exits, by the fstream dtor, the runtime cleanup code, or the kernel, so there shouldn't be a problem if they're separate programs. In a single program you'd have to verify that a single file can opened and manipulated via two different streams pointing in different directions. I'll check the standard when I have a chance. Of course you can use a single fstream is that it a problem. Quote Link to post Share on other sites
iccaros Posted May 18, 2005 Author Report Share Posted May 18, 2005 so in the second one you took out line 14 examplefile.close(); and it still workded (I thought I had taken it out before..)I guess it does not matter since I am putting them in the same program and will read a write so I have to close the file before reading.. Quote Link to post Share on other sites
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.