hi all,
i was trying to write to a pre existent binary file but every time it would change the size of file and remove all of its contents so what i should i do?????

here is an example to what i'am trying to say(it is not exactly the same )

#include <cstdlib>
#include <iostream>
#include <fstream>
using namespace std;

int main(int argc, char *argv[])
{char h[10];
char c,d;
for(int i=0; i<10; i++)
h[i]='a';
ofstream out("file2", ios::out |ios::binary);
if(!out){cout<<"cannot open file.\n";}
out.write((char *) &h, sizeof h );
out.close();
out.open("file2", ios::out |ios::binary);
out.seekp(5,ios::beg);
c='z';
out.put(c);
out.close();
ifstream in("file2", ios::in | ios::binary);
if(!in){cout<<"cannot open file "<<endl;}
while(!in.eof()){
in.get(d);
cout<<d<<endl;
}


system("PAUSE");
return EXIT_SUCCESS;
}

and the output is :

z
z
press any key to continue

while waht i was trying to make is to edit the conetent of the file after writing 10 (a)'s to:


a
a
a
a
a
z
a
a
a
a

Recommended Answers

All 6 Replies

@VBNick
you didn;t got me at all i didn't want to append something to that file(adding at the end of the file) but i want to edit something in the middle of that pre existent file

you can't do it with <fstream>. You have to use <stdio.h>
Try this:

#include <iostream>
#include <stdio.h>
using namespace std;

int main(int argc, char *argv[])
{
	FILE *file;
	if(fopen_s(&file, "file1.txt", "w") != 0)
	{
		cout << "can't open file.\n";
		return 0;
	}

	for(int i = 0; i < 10; i++)
		fputs("a\n", file);

	fclose(file);


	if(fopen_s(&file, "file1.txt", "r+") != 0)
	{
		cout << "can't open file.\n";
		return 0;
	}

	fseek(file , sizeof("a\n") * 5 , SEEK_SET);
	fputs("z", file);
	fclose(file);

	return 0;
}

is not ther any way i can edit that existent file by using fstreaam as i think it would be easier

I assume you are re-opening the same file because you first want to create it and then edit the existing file. There would be no problem if you don't re-open the file and just to seekp and put(c).

What you want is of course possible with fstream, it would be horrible to have to revert to C-code just for this.

Here is how you do it:

out.write((char *) &h, sizeof h );
out.close();

out.open("file2", ios::in |ios::out |ios::binary); // <-- also open with ios::in
out.seekp(5,ios::beg);
c='z';
out.put(c);
out.close();

It's a subtle difference... but if you don't include ios::in the original content is truncated when overwriting existing data (not if you are appending.. then ios::in is not needed).

@thelamb:it works
Thanks sooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo much

and also thaaaaaaaaaaaaaaaaaaaaanks for your effort and time VBNick

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.