查找二进制文件中所有出现的字节序列

时间:2019-09-11 17:51:53

标签: c++ std

请帮助我了解如何使用std::search来获取二进制文件中所有出现的{0x00、0x00、0x00、0x01}。

下面的代码找到第一个匹配项:

std::string NAL = "\x00\x00\x00\x01";
std::ifstream source("somedata.dat", std::ios::binary);
std::istream_iterator<unsigned char> begin(source), end, currNAL;
currNAL = std::search(begin, end, NAL.begin(), NAL.end());

我不知道如何在while循环中使用std::search

2 个答案:

答案 0 :(得分:1)

由于std :: search()返回并迭代到第一个匹配项,因此您可以使用该第一个匹配项作为您(不包括在内)的起点进行再次搜索。

/// <summary>
/// Creates the CSV from a generic list.
/// </summary>;
/// <typeparam name="T"></typeparam>;
/// <param name="list">The list.</param>;
/// <param name="csvNameWithExt">Name of CSV (w/ path) w/ file ext.</param>;
public static void CreateCSVFromGenericList<T>(List<T> list, string csvCompletePath)
{
    if (list == null || list.Count == 0) return;

    //get type from 0th member
    Type t = list[0].GetType();
    string newLine = Environment.NewLine;

    if (!Directory.Exists(Path.GetDirectoryName(csvCompletePath))) Directory.CreateDirectory(Path.GetDirectoryName(csvCompletePath));

    using (var sw = new StreamWriter(csvCompletePath))
    {
        //make a new instance of the class name we figured out to get its props
        object o = Activator.CreateInstance(t);
        //gets all properties
        PropertyInfo[] props = o.GetType().GetProperties();

        //foreach of the properties in class above, write out properties
        //this is the header row
        sw.Write(string.Join(",", props.Select(d => d.Name).ToArray()) + newLine);

        //this acts as datarow
        foreach (T item in list)
        {
            //this acts as datacolumn
            var row = string.Join(",", props.Select(d => $"\"{item.GetType().GetProperty(d.Name).GetValue(item, null)?.ToString()}\"")
                                                    .ToArray());
            sw.Write(row + newLine);

        }
    }
}

我应该注意,这是未经测试的代码,我并不是说这是针对您的确切问题的精确解决方案,只是说明了这一想法。

答案 1 :(得分:0)

这是一个完整的示例,显示了如何使用搜索vector查找所有实例。这些想法仍然适用于您的情况,您只是使用istream_iterator而不是vector迭代器。

#include <vector>
#include <iterator>
#include <iostream>
#include <algorithm>

int main()
{
  std::vector<unsigned char> vec(500);

  for(int i=0; i < 500; i++)
    vec[i] = static_cast<unsigned char>(i % 100);

  std::vector<unsigned char> pattern { 'A', 'B' };

  auto start = vec.begin();  // start searching a beginning
  while ( (start = std::search(start, vec.end(), pattern.begin(), pattern.end())) != vec.end()) {
    std::cout << "Found at index: " << std::distance(vec.begin(), start) << std::endl;
    start++;     // Search after this match on next iteration
  }
  return 0;
}