Question

I have a custom file with mixed data. At the end of the file there's an entire image which I want to retrieve.

The problem is that, when I 'extract' it and paste it into an image file, rdbuf() leaves me some annoying CR LF characters instead of just the LF ones in the original.

I have already opened both streams in binary mode.

using namespace std;

ifstream i(f, ios::in | ios::binary);
bool found = false;     // Found image name
string s;               // String to read to
string n = "";          // Image name to retrieve
while (!found) {
    getline(i, s);
    // Check if it's the name line
    if (s[0]=='-' && s[1]=='|' && s[2]=='-') {
        found = true;
        // Loop through name X: -|-XXXX-|-
        //                      0123456789
        //      Length: 10         3  6
        for (unsigned int j=3; j<s.length()-4; j++)
            n = n + s[j];
    }
}    
ofstream o(n.c_str(), ios::out | ios::binary);

o << i.rdbuf();
Was it helpful?

Solution 2

Solved. The problem were made during the ofstream operation to save the file before opening. Because the file were saved as text (with CR LF), it was opening as text as well.

OTHER TIPS

I made some research and find out that << operator treats input as text and so adjusts \n to \r\n on Windows.

A way to prevent this using the write method instead of <<.

You can do it like this (replacing your last line of code):

// get pointer to associated buffer object
std::filebuf* pbuf = i.rdbuf();
// next operations will calculate file size
// get current position
const std::size_t current = i.tellg();
// move to the end of file
i.seekg(0, i.end);
// get size of file (current position of the end)
std::size_t size = i.tellg();
// get size of remaining data (removing the current position from the size)
size -= current;
// move back to where we were
i.seekg(current, i.beg);
// allocate memory to contain image data
char* buffer=new char[size];
// get image data
pbuf->sgetn (buffer,size);
// close input stream
i.close();
// write buffer to output
o.write(buffer,size);
// free memory
delete[] buffer;  
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top