十六进制值比较并保存到文件 C++

Hex value comparison and save to file C++

我正在用 C++ 读取 H.264 比特流作为 Hex 文件。每当满足某些条件时,我想插入一些字符串。

如附图所示,如果文件中的任何位置出现 00 00 00 01 的十六进制值,我想添加一些文件中 00 00 00 01 之前的 ABC 之类的字符串并将其另存为新文件。现在写我的方法是将 h.264 文件读取为十六进制。将其转换为字符串并进行字符串比较。有什么方法可以直接进行十六进制比较吗?这是我当前的代码

 #include "stdafx.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <iomanip>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
unsigned char x;
string s1,s2,s3;
s2="Mushahid Hussain";
s3="0000000141";
std::ifstream input("d:\Jm\videos\trying2.264", std::ios::binary);
input >> std::noskipws;
while (input >> x) {
    long constant = 0x0000000168;
    std::ostringstream buffer; 

    buffer << std::hex << std::setw(2) << std::setfill('0')
            << (int)x;
    s1=buffer.str();
    if (s1.find(s1) != std::string::npos) {
        cout<<"hello";
    s1+=s2;
}
std::ofstream outfile;

  outfile.open("d:\Jm\bin\trying5.264", std::ios_base::app);
  outfile << s1;

}

    return 0;
}


编辑 1
正如 Tommylee2k 所回答的,我可以附加字符串。但问题是在文件的末尾附加了十六进制 CD 值,如附图所示。

也许更好的方法是将文件二进制文件读入内存缓冲区,然后找到 memcmp()。 当你找到你的模式时,你在匹配之前写入块,然后是你的 "ABC" 字符串,并继续搜索文件的其余部分

#include <stdio.h>
#include <string.h>
#include <memory.h>
#include <malloc.h>

char pattern[4]= { 0x00,0x00,0x01,0x67 };

char *memfind(char *s, int len, char *p, int plen) {
    int n=0;
    char *pos = s;
    while ((pos-s)<(len-plen)) {
        while ( *(pos+n) == *(p+n) && n<=plen) n++;
        if (n==plen) 
            return pos;
        pos++;n=0;
    }
    return NULL;
}

int main() {
    FILE *in = fopen("in.vid", "r+");
    FILE *out = fopen("out.vid", "wb");

    // get Filesize
    size_t size = 0;
    fseek(in, 0L, SEEK_END);
    size = ftell(in);

    // read whole file in
    char *buffer = malloc(size);
    fseek (in, 0L, SEEK_SET);
    fread (buffer, size, 1, in);

    char *currentPos = buffer;
    char *found;
    if (buffer) {
        while (1) {
            found = memfind(currentPos, size-(currentPos-buffer), pattern, sizeof(pattern));
            if (found==NULL) break;
            fwrite(currentPos, 1, (size_t) (found-currentPos), out);
            fwrite("ABC", sizeof("ABC"), 1, out);
            fwrite(pattern, sizeof(pattern),1,out);
            currentPos=found+4;
        }
        fwrite (currentPos, 1, (size_t) size - (currentPos-buffer), out);
        free(buffer);
    }
    fclose (in);
    fclose (out);

    return 0;
}