首页 > 文章列表 > Golang基于文件魔数判断文件类型的案例代码

Golang基于文件魔数判断文件类型的案例代码

golang
499 2023-02-25

本文介绍基于魔数判断文件类型,涉及文件查找读取内容、文件魔数、字节比较,最后还介绍函数参数的知识。

查找位置

File.Seek()函数可以设置偏移位置,为下一次读或写确定偏移量,具体起点有whence确定:0标识相对文件开始位置、1相对当前位置、2相对文件结尾。函数返回新的位置及错误。请看下面示例:

package main
 
import (
   "os"
   "fmt"
   "log"
)
 
func main() {
   file, _ :- os.Open("test.txt")
   defer file.Close()
 
   // Offset 表示偏移量
   // Offset 可以为正数或负数
   var offset int64 - 5
 
   // Whence 偏移参考点,具体取值说明
   // 0 - Beginning of file
   // 1 - Current position
   // 2 - End of file
   var whence int - 0
   newPosition, err :- file.Seek(offset, whence)
   if err !- nil {
      log.Fatal(err)
   }
   fmt.Println("Just moved to 5:", newPosition)
 
   // 从当前位置回走2个字节
   newPosition, err - file.Seek(-2, 1)
   if err !- nil {
      log.Fatal(err)
   }
   fmt.Println("Just moved back two:", newPosition)
 
   // 通过移动零字节返回当前位置
   currentPosition, err :- file.Seek(0, 1)
   fmt.Println("Current position:", currentPosition)
 
   // 回到文件起始点
   newPosition, err - file.Seek(0, 0)
   if err !- nil {
      log.Fatal(err)
   }
   fmt.Println("Position after seeking 0,0:", newPosition)
}

执行程序结果如下:

Just moved to 5: 5
Just moved back two: 3
Current position: 3
Position after seeking 0,0: 0

文件类型

魔数是文件前几个字节,用于唯一标识文件类型,从而无需关注复杂文件结构就能够确定文件类型。举例,jpeg文件总是ffd8 ffe0。下面列举常见文件类型的魔数:

图像文件
File typeTypical extensionHex digits xx - variableAscii digits . - not an ascii char
Bitmap format.bmp42 4dBM
FITS format.fits53 49 4d 50 4c 45SIMPLE
GIF format.gif47 49 46 38GIF8
Graphics Kernel System.gks47 4b 53 4dGKSM
IRIS rgb format.rgb01 da
ITC (CMU WM) format.itcf1 00 40 bb
JPEG File Interchange Format.jpgff d8 ff e0
NIFF (Navy TIFF).nif49 49 4e 31IIN1
PM format.pm56 49 45 57VIEW
PNG format.png89 50 4e 47.PNG
Postscript format.[e]ps25 21%!
Sun Rasterfile.ras59 a6 6a 95Y.j.
Targa format.tgaxx xx xx
TIFF format (Motorola - big endian).tif4d 4d 00 2aMM.*
TIFF format (Intel - little endian).tif49 49 2a 00II*.
X11 Bitmap format.xbmxx xx
XCF Gimp file structure.xcf67 69 6d 70 20 78 63 66 20 76gimp xcf
Xfig format.fig23 46 49 47#FIG
XPM format.xpm2f 2a 20 58 50 4d 20 2a 2f/* XPM */
压缩文件类型
File typeTypical extensionHex digits xx = variableAscii digits . = not an ascii char
Bzip.bz42 5aBZ
Compress.Z1f 9d
gzip format.gz1f 8b
pkzip format.zip50 4b 03 04PK…
归档文件类型
File typeTypical extensionHex digits xx = variableAscii digits . = not an ascii char
TAR (pre-POSIX).tarxx xx(a filename)
TAR (POSIX).tar75 73 74 61 72ustar (offset by 257 bytes)
可执行文件类型
File typeTypical extensionHex digits xx = variableAscii digits . = not an ascii char
MS-DOS, OS/2 or MS Windows4d 5aMZ
Unix elf7f 45 4c 46.ELF

有了上面的基础知识,我们就可以读文件前几个字节判断文件类型。

实现基础函数

首先定义文件魔数标识变量:

var(
   PDF        = []byte{0x25, 0x50, 0x44, 0x46}
	RAR        = []byte{0x52, 0x61, 0x72, 0x21, 0x1A, 0x07, 0x00}
	GZIP       = []byte{0x1F, 0x8B, 0x08}
	ZIP_0      = []byte{0x50, 0x4B, 0x03, 0x04}
	ZIP_1      = []byte{0x50, 0x4B, 0x05, 0x06}
	ZIP_2      = []byte{0x50, 0x4B, 0x07, 0x08}
	WEBP       = []byte{0x52, 0x49, 0x46, 0x46}
   ...
)

下面定义几个读文件函数。

首先是从ReadSeeker开始位置起读取几个字节函数:

func readUntil(l int, r io.ReadSeeker) ([]byte, error) {
	buff := make([]byte, l)

	_, err := r.Read(buff)
	if err != nil {
		return nil, err
	}

	r.Seek(0, io.SeekStart)

	return buff, nil
}

基于魔数字节数组读文件魔数:

func checkBuffer(r io.ReadSeeker, t []byte) ([]byte, error) {
   // 根据提供参数获取长度
	l := len(t)

	buff, err := readUntil(l, r)
	if err != nil {
		return make([]byte, 0), err
	}

	return buff, nil
}

基于参数比较文件魔数:

func genericCompareBuffer(r io.ReadSeeker, t []byte) bool {
	buff, err := checkBuffer(r, t)
	if err != nil {
		return false
	}

	valid := bytes.Compare(t, buff)
	return valid == 0
}

比较文件包括多个魔数情况比较:

func genericMultipleCompareBuffer(r io.ReadSeeker, t [][]byte) bool {
	buff, err := checkBuffer(r, t[0])
	if err != nil {
		return false
	}

	for _, v := range t {
		if bytes.Compare(v, buff) == 0 {
			return true
		}
	}

	return false
}

类型判断函数

有了上面的基础函数,我们可以提供上层应用接口函数。

首先是常用类型判断函数,注意这里PNG、JPEG是前面定义的字节数组变量。

// IsPng function will return true if File is a valid PNG
func IsPng(r io.ReadSeeker) bool {
	return genericCompareBuffer(r, PNG)
}

// IsJpeg function will return true if File is a valid JPEG
func IsJpeg(r io.ReadSeeker) bool {
	return genericCompareBuffer(r, JPEG)
}

// IsPdf function will return true if File is a valid PDF
func IsPdf(r io.ReadSeeker) bool {
	return genericCompareBuffer(r, PDF)
}

// IsGif function will return true if File is a valid GIF
func IsGif(r io.ReadSeeker) bool {
	return genericCompareBuffer(r, GIF)
}

同类文件可能有不同魔数场景:

// IsMpg function will return true if File is a valid MPG
func IsMpg(r io.ReadSeeker) bool {
	return genericMultipleCompareBuffer(r, [][]byte{
		MPG_0,
		MPG_1,
	})
}

最后提供一个同时判断多种文件类型的函数,利用函数类型参数:

// IsOneOf function will validate File with multiple function
func IsOneOf(r io.ReadSeeker, functions ...function) bool {
	for _, f := range functions {
		valid := f(r)
		if valid {
			return true
		}
	}

	return false
}

测试代码

下面测试前面定义的函数,函数包括文件名称参数,判断该文件类型:

package main

import (
	"fmt"
	"os"
)

func main() {
	args := os.Args

	if len(args) < 2 {
		fmt.Println("required input file")
		os.Exit(1)
	}

   // 打开文件
	inputFileArg := args[1]
	inFile, err := os.Open(inputFileArg)

	if err != nil {
		fmt.Println("error open input file ", err)
		os.Exit(1)
	}

   // 支持错误处理的关闭方式
	defer func() { 
      err := inFile.Close() 
      if err != nil {
         fmt.Println("error close input file ", err)
      }
   }()

   // 一次性判断多种类型,如:是否为图像文件
	valid := IsOneOf(inFile, filesig.Is3gp, filesig.IsPng, filesig.IsJpeg)
	fmt.Println(valid)

   // 当然也可以判断单个类型
   valid = filesig.Is3gp(inFile)
	fmt.Println(valid)
}

总结

本文介绍了基于文件魔数判断文件类型的方法,主要涉及如何ReadSeek读取文件指定字节内容,然后介绍文件魔数,最后给出示例基于魔数判断文件类型。参考代码:https://github.com/telkomdev/go-filesig

到此这篇关于Golang基于文件魔数判断文件类型的文章就介绍到这了,更多相关go文件类型内容请搜索程序之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持程序之家!