The basic idea is to read the file contents into memory, say at program start, manipulate the string as desired, then write the entire thing back to the file.
- So you would open and read in Sample.txt. In memory you have a string = "ABCD"
- in your program execution, accept user input of XXX. Insert that into your string with your favorite string manipulation method. Now string = "ABXXXCD"
- Finally you would overwrite Sample.txt with your updated string and close it.
If you were worried about corruption or something, you might save it to a secondary file, then verify its contents, delete the original, and rename the new to be the same as the original.