0
struct RGB {
    int r, g, b;
};

RGB operator>>(std::ifstream& in, RGB& rgb) {
    in >> rgb.r;
    in >> rgb.g;
    in >> rgb.b;
    return rgb;
}

std::ostream& operator<<(std::ostream &out, RGB& rgb) {
    out << rgb.r << " ";
    out << rgb.g << " ";
    out << rgb.b << std::endl;
    return out;
}



int main()
{
    ifstream myFile;
    myFile.open("Image01.ppm", std::ifstream::binary);

    //Check for error
    if (myFile.fail()) 
    {
        cerr << "Error loading file" << endl;
    } else {
        char magic[5];
        int width, heigth;
        int pixelValue;
        myFile >> magic >> width >> heigth >> pixelValue;
        cout << magic << endl << width << endl << heigth << endl << pixelValue << endl;

        RGB rgb;
        int size = width*heigth;
        for (int i = 0;i < size;i++) {
            myFile >> rgb;
            std::cout << rgb;
        }
    }
    myFile.close();
    system("pause");    
    return 0;
}

Hello guys , I have been trying to read a ppm file image but I have some problems , when I read a txt file I have created with the imageType ,width,height and pixelValue and some RGB triplets everything is ok , when I actually try to read the ppm file it reads the imageType ,width,height and pixelValue however when I want it to print the pixels it just prints -858993460 forever, when I change the struct so the rgb value are chars and not ints , I got some weird symbols printed .So how do we print and store binary data in C++ and what am I doing wrong here?

  • 2
    The `>>` input operator treats the file as a *text* file. You can not use them for a binary file. You have to use the [input stream `read` function](http://en.cppreference.com/w/cpp/io/basic_istream/read) to read from binary files. – Some programmer dude Nov 19 '17 at 17:22
  • You seem to be talking about two different things. Do your files start with `P3` or `P6`? – Mark Setchell Nov 19 '17 at 17:28
  • Have you read the ppm file specification? http://netpbm.sourceforge.net/doc/ppm.html Things are little bit more complicated than myFile >> magic >> width >> heigth >> etc. One other thing is to define your "int" size, int8_t for instance (see http://en.cppreference.com/w/cpp/types/integer). The C++ standard says nothing about the int size, only that size of short is <= size of int <= size of long int. In short you cannot assume that int is 16bits for instance. – Picaud Vincent Nov 19 '17 at 17:31
  • Yeah sorry for not being clear enough, the format of the image is P6 always , I will read the links. Thanks in advance! – user1345245 Nov 19 '17 at 17:37

0 Answers0