0

I am trying to write and append to file in binary mode but some how the file is getting corrupted.I cant understand where it is going wrong, m_strReceivedMessage is of type std::string

 const char * c = m_strReceivedMessage.c_str();
 std::ofstream out(file, std::ios::binary | std::ios_base::app | std::ios_base::out);
 int i = m_strReceivedMessage.size();
 if (out.is_open()) {
   out.write(c, i);
 }
 out.close();
gsamaras
  • 66,800
  • 33
  • 152
  • 256
Ajith Kumar
  • 39
  • 1
  • 5
  • The indentation of this post surely does go wrong, for a start. :) – gsamaras Apr 22 '16 at 17:00
  • 2
    I can't tell much from your post. What do you mean by "corrupted"? What did you expect to write, what got written, and how did you determine what was in the written file? – Roddy Apr 22 '16 at 17:04
  • m_strReceivedMessage has some binary content read from pdf file and it has to be written into another pdf file.but after running through the above logic, when I try to open the output pdf file, it pops up an error message "There was an error opening this document. The file is damaged or could not be repaired" – Ajith Kumar Apr 22 '16 at 17:12
  • 3
    But you can't just append stuff to a PDF file! It's got a format, and you must follow it! It's not like appending something to a text file. You can't do it like this, you need a library that can deal with the PDF format. – Fabio says Reinstate Monica Apr 22 '16 at 17:14
  • @AjithKumar, Fabio is right. Moreover, I checked your code, it shouldn't produce something like that, *if your PDF logic was OK*. Check my answer please. – gsamaras Apr 22 '16 at 17:17

1 Answers1

1

Not sure what's wrong, maybe you are getting repeated content.

Change that:

std::ofstream out(file, std::ios::binary | std::ios_base::app | std::ios_base::out);

to that:

std::ofstream out(file, std::ios::binary);

and you should be fine, if your string is fine.

Check this minor example:

#include <iostream>
#include <fstream>
#include <string>
#include <iterator>
#include <vector>

using namespace std;

int main() {
        string m_strReceivedMessage = "foo";
        const char * c = m_strReceivedMessage.c_str();
        ofstream out("test.bin", ios::binary);
        int i = m_strReceivedMessage.size();
        if (out.is_open()) {
                out.write(c, i);
        }
        out.close();

        ifstream input("test.bin", ios::binary );
        // copies all data into buffer
        vector<char> buffer((
            istreambuf_iterator<char>(input)), 
            (istreambuf_iterator<char>()));

        for(unsigned int i = 0; i < buffer.size(); ++i)
                cout << buffer[i] << endl;
        return 0;
}

which outputs:

gsamaras@gsamaras-A15:~$ g++ -Wall px.cpp 
gsamaras@gsamaras-A15:~$ ./a.out 
f
o
o

For more, please read Reading and writing binary file.

Community
  • 1
  • 1
gsamaras
  • 66,800
  • 33
  • 152
  • 256