I need to read the first n bytes from a file, to make sure a file is really a Word file (.docx) (disregarding the extension).
How can I do this?
I need to read the first n bytes from a file, to make sure a file is really a Word file (.docx) (disregarding the extension).
How can I do this?
Read 1st n bytes by fsutil
file truncation (make a copy of original first):
FSUTIL file seteof <file> <n bytes>
Or just fc /b
the first few bytes you're after:
set n=3
set file=test.one
fsutil file createnew A %n%
fc /b A %file% > B & del A
set /a n=%n%-1 >Nul
for /l %j in (0,1,%n%) do cmd /c exit /b %j & set hex=!=exitcode:~-2!& (find "!hex!: "<B || echo doh: la 00)>> A
(for /f "tokens=3" %i in (A) do set /p=%i <nul) & del A & del B
Note:
Either generate binary/null characters from codepage 437 with makecab
& built-in cmd
commands, or fsutil
the null bytes.
Update:
Here's a VBatch hybrid code to get first 3 bytes of a file:
@echo off
echo Set fso=CreateObject("Scripting.FileSystemObject") > some.vbs
echo Set f=fso.OpenTextFile("%~1"):buf=f.Read(3):f.Close >> some.vbs
REM OpenTextFile opens any file as a binary stream; f.read(n) reads the first n bytes of that stream
echo wscript.echo Hex(ASCb(mid(buf,1,1))) ^& "," ^& Hex(ASCb(mid(buf,2,1))) ^& "," ^& Hex(ASCb(mid(buf,3,1))) >> some.vbs
for /f "tokens=1-3 delims=," %%A in ('cscript //nologo some.vbs') do (
set byte1=0%%A
set byte2=0%%B
set byte3=0%%C
)
echo %byte1:~-2% %byte2:~-2% %byte3:~-2%
Tested in Win 10 CMD