Deleting data from the file without deleting the file first

C

crea

This is a simple question, but I have never found an answer to this and been
thinking about it. Plus not sure if this is the right forum, but not sure
where to put this...I guess some kind of general programming guestion.

So we open a file with iofstream and then write /save some text to file.
Lets say we save a text:

"Hello World!!"

To a file HW.txt.

Now, is it possible to delete the character 'o' from the file without
deleting the file HW.txt first?
Currently I think the only way to do this is to read the whole data from
file to a string and then delete it from the string and then save the whole
string to the file.
 
B

Bart van Ingen Schenau

Lets say we save a text:

"Hello World!!"

To a file HW.txt.

Now, is it possible to delete the character 'o' from the file without
deleting the file HW.txt first?

That depends on what you mean with 'delete the file'. You have to rewrite
the entire file, but you don't have to tell the filesystem that the file
is gone before you write it anew.
Currently I think the only way to do this is to read the whole data from
file to a string and then delete it from the string and then save the
whole string to the file.

Yes, that is correct. Note that those steps don't include removing the
file from the filesystem. When you open the file for writing/saving, you
just have to use ios::eek:ut|ios::trunc to ensure the old contents are gone.

Bart v Ingen Schenau
 
N

Nobody

So we open a file with iofstream and then write /save some text to file.
Lets say we save a text:

"Hello World!!"

To a file HW.txt.

Now, is it possible to delete the character 'o' from the file without
deleting the file HW.txt first?

Using only the features of the standard C or C++ libraries, the best you
can do is to shift everything after the "o" back one space, by reading it
in then writing it out at a different offset.

Some operating systems may have the ability to delete chunks from the
middle of the file, but most don't, and the standard library doesn't
provide any mechanism to make use of such a feature.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,982
Messages
2,570,186
Members
46,740
Latest member
JudsonFrie

Latest Threads

Top