Member Avatar for yoni0505

I had a problem with some program I wrote that edit specific values within a specific file.
When I saved the values, using fstream's write() function, everything between these values became null.
I've looked again in the I/O tutorial - http://www.cplusplus.com/doc/tutorial/files/
and saw that they use memory block at the read()/write() example.
I also saw that they are using it at the example in the description about the write() function - http://www.cplusplus.com/reference/iostream/ostream/write/

I open the file and write to it directly. For example:

ofstream saveFile(saveFilePath, ios::binary);
saveFile.seekp(a, ios::beg);
saveFile.write(x,y);
saveFile.seekp(b, ios::beg);
saveFile.write(w,x);
//...

Does my code null everything between the values I write to the file because I directly write it on the opened file and doesn't use a buffer like in the examples?

To answer the question in your title, yes. write's first argument must be a pointer to char where the number of available characters starting at that pointer match the second argument.

everything between these values became null.

Can you elaborate? What do you want to happen (with examples) and what's actually happening (with examples)?

Member Avatar for yoni0505

I have a file that store many values.
I want to edit only few of them.
For example I want to set the value of a short int to 100 at the offset 195.
I want everything else to stay as it is when I opened the file.
But when I close the file, all the other values become null (0), and only the values that I modified stay as I set them.
That means that in the example, everything but the short int at the offset 195, will be 0 (while they had different value from 0 when I opened the file).

I don't know what causing this problem. I saw that in the examples at the links I gave in the first post they used buffer. So I wonder if the problem is caused because I don't use a buffer?

But when I close the file, all the other values become null (0), and only the values I modified stay as they are.

I suspect you're doing more than you say, but each time you open the file strictly for output, it will be truncated to zero length. Try this instead:

fstream saveFile(saveFilePath, ios::in | ios::out | ios::binary);
commented: Helped me to solve a problem! +1
Member Avatar for yoni0505

Thank you Narue, this was the problem!

I wonder why they didn't mention this fact in the tutorial, it's critical :\

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.