Writing to possition in a file

Hi, Can someone tell me what to set my ios to so this works right? I'm trying to make a function that writes a line of text to a set position in a file without overwriting what was already in there. Here's what I've got so far, but it's still just appending to the end of a file.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
bool filePos(string fileName, long positionInFile, char* lineText)//add txt to a set possition, returns 0 if failed to open/write.
{
	ofstream file(fileName, ios::app | ios::binary);
	if(file.is_open() && file.good())
	{
		size_t len = strlen(lineText);
		file.seekp(positionInFile);
		file.write(lineText, len);
		file.close();
	}
	else
	{
		return 0;
	}
}
Last edited on
The easiest way is to read the whole file, make the changes you want to make, and then write it all back to file again.
OK, so I think I've got it, if I set my ios to (ios::in | ios::binary) it will insert the writing in the right place, but it overwrites the characters that were already in that position, so I'll only have to copy the file from that position to the end first, then insert it back into place several lengths down equal to the length of the line I insert.
Thanks Peter87, I think I can handle that. If anyone has a suggestion of a better ios setup I'd take it though, just some of my files I want to modify to are a bit on the long side and I haven't actually used dynamic memory before...
Last edited on
Topic archived. No new replies allowed.