i want to remove some character in my file. too i want to replace some char to another. i know the easiest way for this job is we write final text in file. i mean we first produce sightly text then write it in file .i don't want use of temporary string.what do i do for solving this problem ?
how to remove and replace some char in a file(in c++)?
Collapse
X
-
This is not as easy as it looks.
The common method is to read the file and write it to a temporary file skipping the data to be deleted. Then copying the temporary file back on top of the original.
Depending upon the format of the file, that is, if it is a non-compressed non-encrypted text file you can locate the start and end of the data to be deleted and then copy from the end of the deleted data to the start of the deleted data shifting the last portion of the file forward. You will have bytes allocated to the file at the end that are not part of the shortened file so you will need to reposition the end of file marker. This is not a beginner problem. -
The thing with removing data from a file is that the file gets shorter. That means the excess after the data needs to be removed. So removing the data just adds bytes to the end of the file that aren't part of the file. Ugly.
If you change the data to be deleted to blanks, the data is still there. Now it's blanks and nothing was deleted.
If you change the data t be deleted to some non-data value like 003, then the 003 are there and now every function that reads the file has to smart enough to know that 003 is not a valid data value. Plus now you can't have value 003 in your file. Bad choice.
By far the simplest approach is to read the file and write the data to a temporary file skipping the data to deleted and then copying the temporary back over the original. I know you prefer not to use a temporary but that is the easiest way to go.Comment
Comment