Click here to Skip to main content
15,885,890 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to create a simple C++ application that find a string and replace them to another string in a binary file.

So far, I got some prototyping but it does not work completely. For example, when I try to replace
pepperpepper
to
"appleapple11"
in the file called "test.txt".



Feel boring? Need some fresh things? This page provides 2 random stories by default, all of which are very short but very interesting. We have collected more than 100 stories and you will surely find a lot of fun. This tool generates 2 small stories each time by default, you can generate a specified number of short stories. We added a small feature, click the Russian word with the mouse, it will automatically select the appropriate text, this is a convenient copy tool.
pepperpepper
pepperpepper
pepperpepper
Feel boring? Need some fresh things? This page provides 2 random stories by default, all of which are very short but very interesting. We have collected more than 100 stories and you will surely find a lot of fun. This tool generates 2 small stories each time by default, you can generate a specified number of short stories. We added a small feature, click the Russian word with the mouse, it will automatically select the appropriate text, this is a convenient copy tool.




I only get this broken text after the first string is correctly replaced. Then the rest of text is messed up.


Feel boring? Need some fresh things? This page provides 2 random stories by default, all of which are very short but very interesting. We have collected more than 100 stories and you will surely find a lot of fun. This tool generates 2 small stories each time by default, you can generate a specified number of short stories. We added a small feature, click the Russian word with the mouse, it will automatically select the appropriate text, this is a convenient copy tool.
appleapple11                                                                                                                                                                                            than 100 stories and you will surely find a lot of fun. This tool generates 2 small stories each time by default, you can generate a specified number of short stories. We added a small feature, click the Russian word with the mouse, it will automatically select the appropriate text, this is a convenient copy tool.



It only replace the first
pepperpepper
to
"appleapple11"
, then it produce some weired results after.

I guess the problem is inside the for loop. I had no luck to fix the problem in the for loop.

Your help will be really appreciated.

Kind regards.

What I have tried:

C++
//This loop is not working and producing some incorrect results
for (auto it = itbegin; it < itend; it++)
{
    cp = nullptr;
    cp = strstr(it._Ptr, search_str);

    if (cp)
    {
        foundStrLenght = strnlen(cp, MAX_BUFFER);

        cout << "At address: 0x" << hex << (cp - itbegin._Ptr) << " Found string: " << cp << " Size: " << dec << foundStrLenght << " Bytes" << endl;

        int rpls_str_count = strnlen(replace_str, MAX_BUFFER);


        while (rpls_str_count > foundStrLenght)
        {
            cout << "Replace value length greater than original! Please enter another value:" << endl;
            gets_s(replace_str, MAX_BUFFER);
            rpls_str_count = strnlen(replace_str, MAX_BUFFER);
        }

        strncpy(cp, replace_str, MAX_BUFFER);
        it += rpls_str_count;
        somethingChanged = true;

    }
}



if (somethingChanged == true)
{
    ofstream ofile(ChangeFileName(file_name), ios::out | ios::binary);
    ofile.write((char*)&buffer[0], buffer.size() * sizeof(char));
    ofile.close();
    cout << "Done!" << endl;
}
Posted
Updated 1-Jan-21 4:58am
v4

Replace this line:
C++
for (auto it = itbegin; it < itend; it++)
with this:
C++
for (auto it = itbegin; it != itend; it++)
Since obviously it is not a number value, using the '<' operator probably doesn't do what you expected.
 
Share this answer
 
To start with, that is not a binary file. That makes a big, big difference in how you deal with its data. There is one major caveat to that statement : if the original and replacement strings are of equal length then you can process it like a binary replacement. If they are not then you can't do a straight binary replacement. I have written code to do exactly this in actual binary files and it handles strings of different lengths appropriately. In a binary file that's pretty easy as long as the data expects fixed-length fields. If it doesn't, as in text files, then it's a whole different thing and considerably more difficult.

In your logic you have to make certain the lengths are the same. It needs to be :
while (rpls_str_count != foundStrLenght)
Then, you can replace the string like this :
memcpy(cp, replace_str, foundStrLenght );
Remember - you are opening text.txt and that is a text file - not binary. The reason that uses memcpy is in a text file there are no null characters that terminate strings. It is just plain text with spaces and new line characters. When you use strncpy it will also copy a null character and that will foul things up in a text file.
 
Share this answer
 
Compiling does not mean your code is right! :laugh:
Think of the development process as writing an email: compiling successfully means that you wrote the email in the right language - English, rather than German for example - not that the email contained the message you wanted to send.

So now you enter the second stage of development (in reality it's the fourth or fifth, but you'll come to the earlier stages later): Testing and Debugging.

Start by looking at what it does do, and how that differs from what you wanted. This is important, because it give you information as to why it's doing it. For example, if a program is intended to let the user enter a number and it doubles it and prints the answer, then if the input / output was like this:
Input   Expected output    Actual output
  1            2                 1
  2            4                 4
  3            6                 9
  4            8                16
Then it's fairly obvious that the problem is with the bit which doubles it - it's not adding itself to itself, or multiplying it by 2, it's multiplying it by itself and returning the square of the input.
So with that, you can look at the code and it's obvious that it's somewhere here:
C#
int Double(int value)
   {
   return value * value;
   }

Once you have an idea what might be going wrong, start using the debugger to find out why. Put a breakpoint on the first line of the method, and run your app. When it reaches the breakpoint, the debugger will stop, and hand control over to you. You can now run your code line-by-line (called "single stepping") and look at (or even change) variable contents as necessary (heck, you can even change the code and try again if you need to).
Think about what each line in the code should do before you execute it, and compare that to what it actually did when you use the "Step over" button to execute each line in turn. Did it do what you expect? If so, move on to the next line.
If not, why not? How does it differ?
Hopefully, that should help you locate which part of that code has a problem, and what the problem is.
This is a skill, and it's one which is well worth developing as it helps you in the real world as well as in development. And like all skills, it only improves by use!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900