Writing to a file and not overwriting it

This is a discussion on Writing to a file and not overwriting it within the C++ Programming forums, part of the General Programming Boards category; Hey guys, I'm trying to make a file that records a bunch of data in a file. Well, I want ...

  1. #1
    Registered User
    Join Date
    Sep 2003
    Posts
    27

    Writing to a file and not overwriting it

    Hey guys, I'm trying to make a file that records a bunch of data in a file.

    Well, I want the first line to be the number of entries, and then the entries follow right afterwords.

    The problem is that when I try to overwrite the # of entries on the first line, the whole file is gone except for that one number!

    So, I have the program check if the file exists on startup, and if not, make a new file with the first line being "0", meaning that there are no stored data.

    When something is added, I want that 0 to be changed to 1, 2, etc. The current code just overwrites the whole file, though!

    How can I overwrite the first line without harming the line under it, or any other parts of the file?

    Code follows:

    Code:
    ofstream CoolFile("C:\\recipes.dat", ios::app);
    
    	if (CoolFile)
    	{
    			CoolFile << aryCurr->name << endl;
    			CoolFile << aryCurr->type << endl;
    			CoolFile << aryCurr->difficulty << endl;
    			CoolFile << aryCurr->peopleServed << endl;
    			CoolFile << aryCurr->dateAdded << endl;
    			CoolFile << aryCurr->numIngredient << endl;
    			CoolFile << aryCurr->numInstructions << endl;
    			
    			for (g=0;g <=(numberOfIngredients-1);g++)
    			{
    				CoolFile << aryCurr->ingredients[g].name << endl;
    				CoolFile << aryCurr->ingredients[g].quantity << endl;
    			}
    
    			for (g=0;g <=(numberOfInstructions-1);g++)
    			{
    				CoolFile << aryCurr->instructions[g].instr << endl;
    			}
    			CoolFile.close();
    			ofstream CoolFile("C:\\recipes.dat", ios::ate);
    			CoolFile.seekp(0);
    			CoolFile << *current << endl;
    	}
    	
    	CoolFile.close();
    Thanks!
    sirSolarius

  2. #2
    mustang benny bennyandthejets's Avatar
    Join Date
    Jul 2002
    Posts
    1,401
    Make sure that current contains the right value. I've made a similar bit of code that works fine. Maybe you could post all your code?
    benforbes@optusnet.com.au
    Microsoft Visual Studio .NET 2003 Enterprise Architect
    Windows XP Pro

    Code Tags
    Programming FAQ
    Tutorials

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21