Updating a line in a file

Is it possible to update a line in a file?


The first number of the file is how many names there are in the list.

For example, this is my information.dat file:
0


Then when I want add a new name to the list, it would update the first number and add the name in the next line.

For example:
1
Matthew


Then I want to do it again with a different name.
It should update the first line of code and move to the next line after Matthew.

For example:
2
Matthew
Joseph


But this is not working, does anyone know why?

Here is the code I have right now:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <string>
#include <fstream>
using namespace std;

int main()
{
	int x, account, i = 0;
	string name, nameSearch, endLine, line, newName;
	ifstream readData ("information.dat");
	ofstream readData2 ("information.dat");
	
	if(readData.fail() == true){ // This will check if the file exists or not
	cout << "Error: cannot find file!" << endl;
	system("PAUSE");
	return 1;}

	readData >> i;
	cin >> newName;
	i += 1;
	readData2 << i;
	for (int j = 0; j < i; j++)
	{
		readData2 << "\n";
	}
	readData2 << newName;

	system("PAUSE");
}
Because you read just number of entries from the file.
You should read the entire file, modify it content and save it.
How should I do that?
Okay, I've got it to somewhat work, however, I don't want to store everything to another file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
	int i;
	string name, nameSearch, endLine, line, newName, nameOfCustomer;
	ofstream readData2 ("informationFinal.dat");
	ifstream readData ("information.dat");
	stack<int> numStore;
	stack<string> nameStore;
	
	if(readData.fail() == true){ // This will check if the file exists or not
	cout << "Error: cannot find file!" << endl;
	system("PAUSE");
	return 1;}
	
	cin >> newName;
	readData >> i;
	i = i + 1;
	numStore.push(i);
	getline(readData,line);

	for (int j = 0; j < i -1; j++)
	{
		readData >> nameOfCustomer;
		nameStore.push(nameOfCustomer);
		getline(readData,line);
	}
	nameStore.push(newName);
	
	readData2 << numStore.top() << "\n";
	for (int k = 0; k < i; k++)
	{
		readData2 << nameStore.top() << "\n";
		nameStore.pop();
	}


This reads everything from the file information.dat, then adds a new name and increments the first number by 1 and prints all that to the informationFinal.dat. I don't want it to do that because then I won't be able to update it again.

When I changed ofstream readData2 ("informationFinal.dat"); to ofstream readData2 ("information.dat");, it deleted everything from the file I had and won't be able to read anything. Try it yourself to know what I mean.

Can someone help?
Nevermind, I figured out my problem
Topic archived. No new replies allowed.