How to replace some bytes of a binary file

  • Thread starter Thread starter Mullin Yu
  • Start date Start date
M

Mullin Yu

I have a file, and want to replace some bytes by other bytes e.g.

Old: 1b 25
New: 1b 26 66 31 30 30 59 1b 26 66 58

How to implement? Thanks!
 
Mullin Yu said:
I have a file, and want to replace some bytes by other bytes e.g.

Old: 1b 25
New: 1b 26 66 31 30 30 59 1b 26 66 58

How to implement? Thanks!

You'll need to open a new file, and read in the old file, writing
unchanged bytes to the new file as they are and changing the others.
Then rename the old file to a backup, delete the old file, rename the
new file to the old file, then remove the backup. (If you don't care
too much if something goes wrong, you could just delete the old file
and then rename the new file without bothering with the backup.)
 
but, if i read the file byte by byte, how can i know that it's 1b 25??? if i
want to have a generic solution, how to handle then?

do i need to convert all the bytes from files to string with delimiter like
1b;25;
1b;26;66;31;30;30;59;1b;26;66;58

then, i can use the string replace function and then convert them to array
and write back to stream.

but, any issue if the file size is very large.

thanks!
 
Mullin Yu said:
but, if i read the file byte by byte, how can i know that it's 1b 25???

You'll need some kind of table saying, "If the first byte is 1b, then
don't write it yet, but remember that I've received it; if the next
byte is 25 then write the replaced version, otherwise write 1b and then
the received byte."
if i want to have a generic solution, how to handle then?

As above, but in a generic way. Basically, for any byte received, you
either know that it (and possibly some "stored" bytes) should be
written as they are, or that you've come to the end of a path and
should write out a different load of bytes instead.
do i need to convert all the bytes from files to string with delimiter like
1b;25;
1b;26;66;31;30;30;59;1b;26;66;58

then, i can use the string replace function and then convert them to array
and write back to stream.

Converting to a string and back would be a bad idea, IMO. Text and
binary should not be confused. Unless, of course, it's actually a text
file to start with...
but, any issue if the file size is very large.

Yes - loading the whole thing into memory at once is a bad idea if it's
large.
 
Back
Top