Opening a file as binary and editing it

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • abdoelmasry
    New Member
    • Oct 2006
    • 104

    #1

    Opening a file as binary and editing it

    Hi All
    Please any one can help me to complete my code !
    My code is about opening file as binary and edit it

    #include <iostream>
    #include <iostream>
    using namespace std;

    int main(){
    fstream nfile;
    nfile.open("new .txt",ios::in|i os::out|ios::bi nary);
    nfile.seekp(2);
    nfile<<"code";
    return 0;
    }

    my main problem is:
    I need to insert my text in file after the position that i have set pointer on it
    but
    without replacing any data from file
    Ex:.

    if the file have string:
    EGYHK.COM

    i want this text be (EGcodeYHK.COM)
    but when i run my code.. it's delete any characters after starting pointer place
    i got it:
    EGcodeCOM
    not
    EGcodeYHK.COM

    sorry im not so good in english
    i hope that i explained my mean
    I Want To Put String Not Write it above the existing string in the file

    Thank You
  • vinothg
    New Member
    • Oct 2006
    • 21

    #2
    When you open the binary file add ios::ate so that the string will get appended instead of overwriting i.e

    nfile.open("new .txt",ios::in|i os::out|ios::at e|ios::binary);

    Hope it will work !!!

    Comment

    • abdoelmasry
      New Member
      • Oct 2006
      • 104

      #3
      Thank You vinothg for Help
      But
      this code will add my code at the end of file
      i need to add it at the before the first line of file

      -i have this string in a file:(is my love)

      -i need to add string (programming) to the file

      -your code using ios::ate will make string in my file: (is my love programming)

      -i want it : (programming is my love)


      Thanks

      Comment

      • vinothg
        New Member
        • Oct 2006
        • 21

        #4
        Ok if you know the exact offset where you want to append then this piece of code may help you.

        #include <iostream>
        #include <fstream>
        using namespace std;

        int main(){
        ofstream os("test",ios:: out|ios::app|io s::binary);
        os.seekg(20,ios ::beg);
        char buffer[3] = {"Hi"}
        os.write((char* )(&buffer),size of(buffer));
        os.close();
        }

        Comment

        • abdoelmasry
          New Member
          • Oct 2006
          • 104

          #5
          i found this code in many forums
          i think it's right but it's not working with me
          i always found a strange characters in test file

          Comment

          Working...