Wolfram Function Repository
Instant-use add-on functions for the Wolfram Language
Function Repository Resource:
Overwrite part of a file with binary data
ResourceFunction["BinaryWriteAt"][path,bytes,offset] writes bytes to path beginning at the position given by offset. | |
ResourceFunction["BinaryWriteAt"][path,bytes] uses an offset of zero. |
"file" | a string corresponding to a local file path |
File["file"] | a local file path |
"str" | a string |
ByteArray[…] | a byte array |
{b1,b2,…} | a sequence of byte values given as integers |
Create a test file:
In[1]:= | ![]() |
Out[1]= | ![]() |
Overwrite the first few bytes of the file with new data:
In[2]:= | ![]() |
Out[2]= | ![]() |
Overwrite a different part of the file:
In[3]:= | ![]() |
Out[3]= | ![]() |
In[4]:= | ![]() |
Out[4]= | ![]() |
In[5]:= | ![]() |
Use a negative value to specify an offset from the end of the file:
In[6]:= | ![]() |
In[7]:= | ![]() |
Out[7]= | ![]() |
In[8]:= | ![]() |
Use UpTo to avoid out-of-range errors:
In[9]:= | ![]() |
In[10]:= | ![]() |
Out[10]= | ![]() |
In[11]:= | ![]() |
Out[11]= | ![]() |
In[12]:= | ![]() |
Out[12]= | ![]() |
In[13]:= | ![]() |
Create a test file with "ISO8859-7" character encoding:
In[14]:= | ![]() |
By default, BinaryWriteAt uses "UTF-8" encoding when writing strings:
In[15]:= | ![]() |
Out[15]= | ![]() |
Reset the test file:
In[16]:= | ![]() |
Specify an alternate encoding to write the correct bytes:
In[17]:= | ![]() |
Out[17]= | ![]() |
In[18]:= | ![]() |
Modify one value in a data file:
In[19]:= | ![]() |
Out[19]= | ![]() |
In[20]:= | ![]() |
Out[20]= | ![]() |
In[21]:= | ![]() |
Out[21]= | ![]() |
In[22]:= | ![]() |
Create a huge test file:
In[23]:= | ![]() |
Out[23]= | ![]() |
BinaryWriteAt can efficiently modify bytes without needing to read the entire file:
In[24]:= | ![]() |
Out[24]= | ![]() |
Check the first few bytes:
In[25]:= | ![]() |
Out[25]= | ![]() |
The performance is not dependent on the file position:
In[26]:= | ![]() |
Out[26]= | ![]() |
Check the last few bytes:
In[27]:= | ![]() |
Out[27]= | ![]() |
In[28]:= | ![]() |
This work is licensed under a Creative Commons Attribution 4.0 International License