delete char from binary file
I want to delete a char/string from a binary/text file. If I know the position of the char/string from the file, how can I delete it? Should I read the file (BlockRead), remove the char/string (with Delete(source, startPos, endPos) and then write (BlockWrite) to a new file or I can delete directly from the specified fi开发者_开发问答le?
thanks
You could use TFileStream.CopyFrom method to copy up to before the unwanted string, seek past it, and then CopyFrom again the remainder of the file. TFileStreams are quite fast.
Something like this (untested)
aInFile := TFileStream.Create(sInput, fmOpenRead);
try
aOutFile := TFileStream.Create(sOutput, fmCreate);
try
aOutFile.CopyFrom(aInFile, Pos);
aInFile.Seek(Skip);
aOutFile.CopyFrom(aInFile, aInfile.Size - Pos - Skip);
finally
aOutFile.Free;
end;
finally
aInFile.Free;
end;
You probably need to read and write the entire file, or at least all the bytes after the point from which you delete the character.
It is sometimes better to come up with a way to avoid deleting the character - i.e empty spaces in the file.
精彩评论