「Swift入門」マジックバイト(最初の4バイト)でzipファイルを判定するサンプル

2020年11月10日

最初の4バイト
50 4b 03 04
使用例1

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
if let fh = FileHandle(forReadingAtPath: "/data/bak/test01.zip") {
let data = fh.readData(ofLength: 4)
if data.starts(with: [0x50, 0x4b, 0x03, 0x04]) {
// some code
}
fh.closeFile()
}
if let fh = FileHandle(forReadingAtPath: "/data/bak/test01.zip") { let data = fh.readData(ofLength: 4) if data.starts(with: [0x50, 0x4b, 0x03, 0x04]) { // some code } fh.closeFile() }
 if let fh = FileHandle(forReadingAtPath: "/data/bak/test01.zip") {
    let data = fh.readData(ofLength: 4)
    if data.starts(with: [0x50, 0x4b, 0x03, 0x04]) {
        // some code
    }
    fh.closeFile()
}

使用例2

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
NSFileHandle *fh = [NSFileHandle fileHandleForReadingAtPath:@"/data/bak/test02.zip"];
NSData *data = [fh readDataOfLength:4];
if ([data length] == 4) {
const char *bytes = [data bytes];
if (bytes[0] == 'P' && bytes[1] == 'K' && bytes[2] == 3 && bytes[3] == 4) {
// some code
}
}
NSFileHandle *fh = [NSFileHandle fileHandleForReadingAtPath:@"/data/bak/test02.zip"]; NSData *data = [fh readDataOfLength:4]; if ([data length] == 4) { const char *bytes = [data bytes]; if (bytes[0] == 'P' && bytes[1] == 'K' && bytes[2] == 3 && bytes[3] == 4) { // some code } }
NSFileHandle *fh = [NSFileHandle fileHandleForReadingAtPath:@"/data/bak/test02.zip"];
NSData *data = [fh readDataOfLength:4];
if ([data length] == 4) {
    const char *bytes = [data bytes];
    if (bytes[0] == 'P' && bytes[1] == 'K' && bytes[2] == 3 && bytes[3] == 4) {
        // some code
    }
}

 

Swift

Posted by arkgame