如何解决如何以特定偏移量将十六进制代码写入文件
我正在使用 Javascript 并想将十六进制代码写入文件的特定偏移量。我知道偏移量 008DD4C0 有可用空间,所以我只是想在这个位置添加一些十六进制代码,但是没有写入
fs.open(filepath.filePaths[0],"r+",(err,fd) => {
if(!err) {
var offset = '008DD4C0'
var position = 9294944 //Decimal equivalent of offset
fs.write(fd,new Uint8Array(['00','00']),1,position,bw,buf) => {
console.log(bw)
console.log(buf)
if(!err) {
// succesfully wrote byte to offset
} else{
}
}
);
} else{
console.log('error')
}
});
解决方法
根据 docs fs.write()
的第三个参数是偏移量(在数组中),第四个是要写入的块长度。 (你的长度为 0 所以什么都没写)。
fs.write(fd,buffer[,offset[,length[,position]]],callback)
这是结果代码:
fs.open(filepath.filePaths[0],"r+",(err,fd) => {
if (!err) {
// var offset = '008DD4C0'
const position = 0x8DD4C0
const data = new Uint8Array([0x00,0x00]) // converted to numbers,Uint8Array ignores strings
fs.write(fd,data,data.length,position,bw,buf) => {
console.log(bw)
console.log(buf)
if (!err) {
// succesfully wrote byte to offset
} else {
}
}
);
} else {
console.log('error')
}
});
更新:另一个问题是调用 Uint8Array 时需要传递数字数组
使用空文件和 new Uint8Array([0xAA,0xBB])
作为 data
进行测试。
结果是末尾带有 AABB 的零文件:
% hexdump test.txt
0000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
*
08dd4c0 aa bb
08dd4c2
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。