View Single Post
Old Jan 10th, 2007, 1:53 PM   #7
DaWei
Resident Grouch
 
DaWei's Avatar
 
Join Date: Jun 2005
Posts: 6,453
Rep Power: 10 DaWei is on a distinguished road
That's not clear, either, but oh well. You're doing things the hard way, too, but let's also ignore that for the moment. If I take the bare bones of your code and clean it up a mere tad, so that it looks like this,
#include <iostream>
#include <cstdio>
#include <string>

using std::cin;
using std::cout;
using std::endl;
using std::cerr;
using std::string;

int main (int argc, char *argv [])
{
	FILE *myFile;
	string sname = "data.txt";
	int myNumber = 10;

	if ((myFile = fopen (sname.c_str(), "w+b")) != NULL) 
	{ 
		fwrite (&myNumber, sizeof (myNumber), 1, myFile);
		cout << "myNumber is: " << myNumber << endl; 
		myNumber = 0;
		cout << "myNumber has been reset to 0."  << endl;       
		fclose(myFile); 
	}      
	else cout << "Error: File not loaded!" << endl;

	if ((myFile = fopen (sname.c_str(), "r+b")) != NULL) 
	{ 
		cout << "Reading previous number from data.txt..." << endl;  
		fread(&myNumber, sizeof(myNumber), 1, myFile); 
		cout << "myNumber from data.txt is: " << myNumber << endl;      
	}      
    else cout << "Error: File not loaded!" << endl;

	cin.get ();
	return 0;
}
The output is this,
Quote:
Originally Posted by Output
myNumber is: 10
myNumber has been reset to 0.
Reading previous number from data.txt...
myNumber from data.txt is: 10
Comment?
__________________
Abstraction doesn't make it impossible to write bad code; it makes it possible to write superior code.
Contributor's Corner: Grumpy on C++ Exceptions DaWei on Pointers
DaWei is offline   Reply With Quote