OK, so ive started work on learning to work with the PPM file format. (im still learning C++ here btw, as you will see). Please take a look at the following code, comment, abuse, break, critize, but please above all, let me know if im missing anything, or anything that i could do better. Tested with a .ppm file created with gimp.
Oh and yes i am aware that the beginning of the netpbm image files begin with the magic number "P*" in the first two characters with a the third character being a "\n", so feel free to point that my for loop is useless =]
Compiles and runs fine on a *nix system
Code:
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char *argv[])
{
int length, bufferlength;
char * buffer;
string newbuffer,magicno;
// Read the file into a buffer (binary mode)
ifstream is;
is.open ("Untitled.ppm", ios::binary );
is.seekg (0, ios::end);
length = is.tellg();
is.seekg (0, ios::beg);
buffer = new char [length];
is.read (buffer,length);
is.close();
//Now check to see if the file is in a valid ppm format.
// From the buffer, check the first two characters before a new line character to get its magic no
newbuffer = buffer;
magicno = newbuffer.substr(0,2);
bufferlength = newbuffer.length();
// first we need to find the first newline character
for (int i = 0; i < bufferlength; i++)
{
// Check for a newline.
if (i > 20) { // large check i know. (ignore this pl0x)
cout << "Unable to find header at start of the file. Aborting.";
} else {
if (newbuffer.substr(i,1) == "\n") {
magicno = newbuffer.substr(0,i);
break;
}
}
}
// Now check the "magicno"
if (magicno == "P3" || magicno == "P6")
{
// Found the P3 / P6 header from the PPM file format.
cout << "Detected PPM Format: " << magicno << "\n";
} else {
// No header found.
}
return 0;
}
Any and all comments, both positive and negative, appreciated.