Reading ppm file C++

4.6k views Asked by At

I am trying to read a ppm file and store its contents in an array. I am starting off by trying to display it but I can't seem to output anything.

char magic;
ifstream myfile;
myfile.open(file,ios::in | ios::binary);
  if (!myfile.is_open()) 
   {
      cout<<"Failed to open";
   }
myfile.get(magic);
if(myfile) cout <<magic <<"not working";
myfile.close();

The file is opened but I can't read it. I have also tried outputting by using the << operators, but no luck there either.

1

There are 1 answers

3
Poriferous On BEST ANSWER

It's probable that your file is being read, but your variable isn't storing all the values therein. I suggest adding this instead of myfile.get(magic):

char magic;
ifstream myfile;

if (!myfile.open(file, ios::in | ios::binary)
{
    cout << "Failed to open" << endl;
}

vector<char> magicNumbers;
while (myfile >> magic)
{
    magicNumbers.push_back(magic);
}
myfile.close();

As you can see, you should store all the values in some kind of array, here I used a vector for flexibility. The rest is up to you.