我正在尝试编写一个简单的程序,该程序将二进制文件的内容打开到缓冲区中,并在该缓冲区中搜索是否出现字符串“ +”。即使我的算法有点不稳定,似乎也确实找到了这些字符。找到它们后,它将字符更改为其他字符。然后,它将相同的缓冲区写回到文件中。它不起作用,因为我尝试在十六进制编辑器中打开文件,并且找不到带有新字符的新字符串。被修改的文件会打印出我正在尝试使用fread和fwrite修改的字符串。
这是代码:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
using namespace std;
char XyZ[] = "++++++++++++++++++++++++++"; //26 count
int main()
{
int error = 0;
FILE * pFile;
unsigned int lSize;
char * buffer;
size_t result;
int i = 0, j = 0;
bool bfound = false;
int count = 0;
int startLocation = 0;
pFile = fopen ( "E:\\DEVS\\Projects\\JustTesting\\FOpen\\Release\\Test.exe", "rb+" );
if (pFile==NULL)
{
cout << "Unable to open Test.exe" << endl;
cout << GetLastError() << endl;
}
else
{
cout << "Successfully opened the file" << endl;
// obtain file size:
fseek (pFile , 0 , SEEK_END);
lSize = ftell (pFile);
rewind (pFile);
cout << "Number of file size is " << lSize << endl;
// allocate memory to contain the whole file:
buffer = (char*) malloc (sizeof(char)*lSize);
if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);}
// copy the file into the buffer:
result = fread (buffer,1,lSize,pFile);
cout << "Total bytes read into our buffer is " << result << endl;
if (result != lSize)
{
cout << "Error in reading the file" << endl;
}
else
{
for(i = 0; i < lSize; i++)
{
if(buffer[i] == '+') // '+'
{
//cout << "Found first one" << endl;
startLocation = i;
//j = i + 1;
//cout << "Found the next one" << endl;
while(buffer[++i] == '+')
{
buffer[i] = '@';
cout << "Found the next one" << endl;
count++;
}
}
}
cout << "Found our string with count " << count << endl;
}
//for(int k = startLocation; k < startLocation + 5; k++)
// buffer[k] = '@';
int value = fwrite (buffer , 1 , lSize , pFile );
cout << "bytes written to file is :" << value << endl;
fclose (pFile);
free (buffer);
}
return 0;
}
最佳答案
第一个问题是您的while
:
while(buffer[++i] == '+')
因此,您已经找到了
+
,但是在while
中,您首先增加了排名,然后测试该值是否仍为+
。如果只有一个+
(如果有多个fread
,则第一个不会被覆盖),该操作将失败。而是将其替换为:for ( ; (buffer[i] == '+') && (i < lSize) ; i++)
下一个问题是在
fwrite
之后,文件位置在末尾。因此,您对rewind(pFile);
的调用将附加修改后的缓冲区。要实际覆盖文件,您首先需要再次调用fread
。关于
fwrite
/ lSize
的最后说明:读取和写入result
项,每个项1个字节。这非常慢(尝试使用一个1兆字节的文件)。相反,您可能想要相反的情况:result = fread(buffer, lSize, 1, pFile);
请注意,成功后,
1
仅具有fwrite
。 也是如此。