gpt4 book ai didi

c++ - 如何在二进制文件中查找字符串?

转载 作者:行者123 更新时间:2023-11-30 02:15:34 25 4
gpt4 key购买 nike

我想在二进制文件中找到一个特定的字符串“fileSize”。
找到该字符串的目的是获取该字符串旁边的 4 个字节,因为这 4 个字节包含我想要读取的数据大小。

二进制文件的内容如下:

同一个字符串在另一个位置:

另一个位置:

下面是将数据写入文件的函数:

void W_Data(char *readableFile, char *writableFile) {
ifstream RFile(readableFile, ios::binary);
ofstream WFile(writableFile, ios::binary | ios::app);

RFile.seekg(0, ios::end);
unsigned long size = (unsigned long)RFile.tellg();
RFile.seekg(0, ios::beg);

unsigned int bufferSize = 1024;
char *contentsBuffer = new char[bufferSize];

WFile.write("fileSize:", 9);
WFile.write((char*)&size, sizeof(unsigned long));
while (!RFile.eof()) {
RFile.read(contentsBuffer, bufferSize);
WFile.write(contentsBuffer, bufferSize);
}
RFile.close();
WFile.close();
delete contentsBuffer;
contentsBuffer = NULL;
}

此外,搜索字符串的函数:

void R_Data(char *readableFile) {
ifstream RFile(readableFile, ios::binary);

const unsigned int bufferSize = 9;

char fileSize[bufferSize];
while (RFile.read(fileSize, bufferSize)) {
if (strcmp(fileSize, "fileSize:") == 0) {
cout << "Exists" << endl;
}
}
RFile.close();
}

如何在二进制文件中查找特定的字符串?

最佳答案

我想到使用 find()是搜索模式的简单方法。

void R_Data(const std::string filename, const std::string pattern) {
std::ifstream(filename, std::ios::binary);
char buffer[1024];

while (file.read(buffer, 1024)) {
std::string temp(buffer, 1024);
std::size_t pos = 0, old = 0;

while (pos != std::string::npos) {
pos = temp.find(pattern, old);
old = pos + pattern.length();
if ( pos != std::string::npos )
std::cout << "Exists" << std::endl;
}
file.seekg(pattern.length()-1, std::ios::cur);
}
}

关于c++ - 如何在二进制文件中查找字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56029064/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com