[iOS Tips]读取文件的头8字节和尾8字节的十六进制

摘自移动开发精英群 ,一般可用来判断未知类型的文件类型

#import "ParseFile.h"
#include 
#include 
using namespace std;
@implementation ParseFile

/**
* 读取文件的头8字节和尾8字节的十六进制
*/
+ (NSString *)getStringWithEight:(NSString *)imagePath
{
    // 2. OC字符串对象转C语言字符串
    NSString *stringOBJ = imagePath;
    const char *resultCString = NULL;
    if ([stringOBJ canBeConvertedToEncoding:NSUTF8StringEncoding]) {
        resultCString = [stringOBJ cStringUsingEncoding:NSUTF8StringEncoding];
    }
    //char const *resultCString = [imagePath UTF8String];
    string str_ab;
    getFileAbstract(str_ab, resultCString);
    NSLog(@"%s", str_ab.c_str());
    NSString *str = [NSString stringWithFormat:@"%s",str_ab.c_str()];
    NSLog(@"%@", str);
    return str;
}

/**
 *  取一个文件的前8个字节的16位和8个字节的16位
 */
void getFileAbstract(string &str_abstract, string filepath)
{
    FILE* pFile = fopen(filepath.c_str(), "rb");
    if (pFile == 0) return;
    char buf[16] = {0};
    fread(buf, 1, 8, pFile);
    fseek(pFile, -8, SEEK_END);
    fread(buf+8, 1, 8, pFile);
    
    int i = 0;
    while (i<16) {
        char temp[3] = {0};
        sprintf(temp, "%.2x", 0xff&buf[i]);
        str_abstract += temp;
        NSLog(@"%s", __func__);
        i = i + 1;
        NSLog(@"i = %d", i);
    }
}

@end

-------调用分割线----

- (void)testParseFile{
    NSString *path =  [[NSBundle mainBundle] pathForResource:@"kkk" ofType:@"jpg"];
    NSString *outString  = [ParseFile getStringWithEight:path];
    NSLog(@"OutString--- %@",outString);
}

你可能感兴趣的:([iOS Tips]读取文件的头8字节和尾8字节的十六进制)